Excel VBA - Looking up a string with wildcards

做~自己de王妃 提交于 2020-01-24 12:08:05

问题


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

回答1:


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



回答2:


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




回答3:


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 *).



来源:https://stackoverflow.com/questions/45436891/excel-vba-looking-up-a-string-with-wildcards

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!