SBozhko
SBozhko

Reputation: 315

Excel VBA - Looking up a string with wildcards

Im trying to look up a string which contains wildcards. I need to find where in a specific row the string occurs. The string all take form of "IP##W## XX" where XX are the 2 letters by which I look up the value and the ## are the number wildcards that can be any random number. Hence this is what my look up string looks like :

FullLookUpString = "IP##W## " & LookUpString

I tried using the Find Command to find the column where this first occurs but I keep on getting with errors. Here's what I had so far but it doesn't work :L if anyone has an easy way of doing. Quite new to VBA -.-

Dim GatewayColumn As Variant
Dim GatewayDateColumn As Variant
Dim FirstLookUpRange As Range
Dim SecondLookUpRange As Range

FullLookUpString = "IP##W## " & LookUpString

Set FirstLookUpRange = wsMPNT.Range(wsMPNT.Cells(3, 26), wsMPNT.Cells(3, lcolumnMPNT))

Debug.Print FullLookUpString

GatewayColumn = FirstLookUpRange.Find(What:=FullLookUpString, After:=Range("O3")).Column

Debug.Print GatewayColumn

Upvotes: 2

Views: 4934

Answers (3)

Gary's Student
Gary's Student

Reputation: 96753

If we can assume that ALL the strings in the row match the given pattern, then we can examine only the last three characters:

Sub FindAA()
    Dim rng As Range, r As Range, Gold As String
    Set rng = Range(Range("A1"), Cells(1, Columns.Count))

    Gold = " AA"

    For Each r In rng
        If Right(r.Value, 3) = Gold Then
            MsgBox r.Address(0, 0)
            Exit Sub
        End If
    Next r
End Sub

enter image description here

Upvotes: 1

Robin Mackenzie
Robin Mackenzie

Reputation: 19319

Per the comment by @SJR you can do this two ways. Using LIKE the pattern is:

IP##W## [A-Z][A-Z]

Using regular expressions, the pattern is:

IP\d{2}W\d{2} [A-Z]{2}

Example code:

Option Explicit

Sub FindString()

    Dim ws As Worksheet
    Dim rngData As Range
    Dim rngCell As Range

    Set ws = ThisWorkbook.Worksheets("Sheet1") '<-- set your sheet
    Set rngData = ws.Range("A1:A4")

    ' with LIKE operator
    For Each rngCell In rngData
        If rngCell.Value Like "IP##W## [A-Z][A-Z]" Then
            Debug.Print rngCell.Address
        End If
    Next rngCell

    ' with regular expression
    Dim objRegex As Object
    Dim objMatch As Object

    Set objRegex = CreateObject("VBScript.RegExp")
    objRegex.Pattern = "IP\d{2}W\d{2} [A-Z]{2}"
    For Each rngCell In rngData
        If objRegex.Test(rngCell.Value) Then
            Debug.Print rngCell.Address
        End If
    Next rngCell

End Sub

Upvotes: 3

Michał Turczyn
Michał Turczyn

Reputation: 37337

Try this:

If FullLookUpString Like "*IP##W##[a-zA-Z][a-zA-Z]*" Then
    MsgBox "Match is found"
End If

It will find your pattern (pattern can be surrounded by any characters - that's allowed by *).

Upvotes: 0

Related Questions