简体   繁体   中英

Excel VBA Macro: Using regex to return adjacent row data

Alright; so here's the whole thing I'm suppose to do.

Input a number that corresponds with a number in Data Worksheet Column A and return the adjacent row data.

I want it to return the adjacent cells; example. If it finds 052035 in cell A5378, I Want it to return the data or cell numbers B5378, C5378

EDIT: I've deleted my code; since it didn't really follow with a good way to do it.

Worksheet Structure for Data: A 1-7800ish[6 Digit number 1-9]

B 1-7800ish Area Codes

C 1-7800ish City/States

The data by the way; is a relatively large set that I got from a query on a SQL-Server. The string number that I'm looking for should have no duplicates based on my original query. [I grouped by before copying it over]

If ya'll have resources for a quick introduction to VB from a programming perspective that'll be helpful. I can program in C/C++ but the syntax in VB is a little weird to me.

If your end goal is to simply find the exact match in column A, and return the values in corresponding row, columns B & C, Regular Expressions is the wrong tool for the job. Use built in functions like Match .

I still don't understand the point of this exercise, as, the data is already arranged in columns A, B and C., you could simply use AutoFilter... This subroutine simply tells you that the value is found (and returns the corresponding data) or not found.

I have tested this (made a small change in dimensioning vals variable)

Sub Foo()
    Dim valToLookFor As String
    Dim rngToLookAt As Range
    Dim foundRow As Long
    Dim vals() As Variant

    valToLookFor = "052035"
    Set rngToLookAt = Range("A:A")

    If Not IsError(Application.Match(valToLookFor, rngToLookAt, False)) Then
        foundRow = Application.Match(valToLookFor, rngToLookAt, False)
        ReDim vals(1)
        vals(0) = rngToLookAt.Cells(foundRow).Offset(0, 1).Value
        vals(1) = rngToLookAt.Cells(foundRow).Offset(0, 2).Value

        'Alternatively, to return the cell address:
        'vals(0) = rngToLookAt.Cells(foundRow).Offset(0,1).Address
        'vals(1) = rngToLookAt.Cells(foundRow).Offset(0,2).Address
        MsgBox Join(vals, ",")
    Else:
        Erase vals
        MsgBox valToLookFor & " not found!", vbInformation
    End If

End Sub

Here is proof that it works:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM