我试图查找包含通配符的字符串。我需要找到特定行中字符串出现的位置。字符串都采用“IP ## W ## XX”的形式,其中XX是我查找值的2个字母,##是可以是任意随机数的通配符号。因此,这就是我的查找字符串的样子:
FullLookUpString = "IP##W## " & LookUpString
我尝试使用Find
命令查找第一次出现的列,但我仍然遇到错误。这是我到目前为止所做的,但它不起作用:L如果有人有一个简单的方法。 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
答案 0 :(得分:3)
根据@SJR的评论,你可以通过两种方式做到这一点。使用LIKE
模式是:
IP##W## [A-Z][A-Z]
使用正则表达式,模式为:
IP\d{2}W\d{2} [A-Z]{2}
示例代码:
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
答案 1 :(得分:1)
如果我们可以假设行中的所有字符串都与给定的模式匹配,那么我们只能检查最后三个字符:
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
答案 2 :(得分:0)
试试这个:
If FullLookUpString Like "*IP##W##[a-zA-Z][a-zA-Z]*" Then
MsgBox "Match is found"
End If
它会找到你的模式(模式可以被任何字符包围 - *
允许)。