dhu*_*ton 2 excel vba text-parsing
我不知道为什么这不起作用。它是一个更大的子例程的一部分,但我已将问题范围缩小到与 InStr 函数一起使用通配符。
我尝试尽可能多地查找有关 InStr 和通配符的信息,据我所知,这应该可行。但事实并非如此。
Dim String1 As String
Dim String2 As String
Dim TestString As String
Dim Location As Integer
String1 = "Hello"
String2 = "Goodbye"
TestString = "Hello and Goodbye"
Location = InStr(1, TestString, (String1 & "*" & String2), vbTextCompare)
If Location >= 1 then
'Do Something
End If
Run Code Online (Sandbox Code Playgroud)
好吧,我已经根据人们的建议尝试了一些事情,现在我正处于这个阶段......
Dim SourceString As String
Dim TestString As String
Dim TempArray() As String
SourceString = "Hello and Goodbye"
TestString = "hello * goodbye"
TempArray = Split(TestString, "*")
If SourceString Like _
Chr(42) & TempArray(0) & Chr(42) & TempArray(1) & Chr(42) Then
Found = True
End If
Run Code Online (Sandbox Code Playgroud)
我已经对 TempArray 的每个部分进行了 debug.print,它包含空格,所以我知道它是正确分割的。
我现在缺少什么?:(
小智 5
InStr函数不使用模式匹配,因此您的通配符星号将被视为字面星号字符(例如Chr(42))。
也许切换到Like模式匹配会产生更好的布尔评估。
'method 1
If TestString Like Chr(42) & String1 & Chr(42) And _
TestString Like Chr(42) & String2 & Chr(42) Then
'Do Something
End If
'method 2
If TestString Like Chr(42) & String1 & Chr(42) & String2 & Chr(42) Then
'Do Something
End If
Run Code Online (Sandbox Code Playgroud)
或者,使用一系列 InStr 函数来确保 String1 和 String2 的匹配顺序正确。
'method 1
If CBool(InStr(1, TestString, String1, vbTextCompare)) And _
InStr(1, TestString, String2, vbTextCompare) > InStr(1, TestString, String1, vbTextCompare) Then
'Do Something
End If
'method 2
dim p as long
If CBool(InStr(1, TestString, String1, vbTextCompare)) Then
p = InStr(1, TestString, String1, vbTextCompare) + Len(String1)
If CBool(InStr(p, TestString, String2, vbTextCompare)) Then
'Do Something
End If
End If
Run Code Online (Sandbox Code Playgroud)