我不知道为什么这不起作用。它是一个更大的子程序的一部分,但我已经将问题缩小到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
好吧,我已经根据人们的建议尝试了一些东西,现在我正处于这个阶段。。。
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
我已经对TempArray的每个部分进行了debug.print,其中包括空格,所以我知道它是正确的拆分。
我现在缺少什么?:(
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
或者,使用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
InStr(1, TestString, (String1 & "*" & String2), vbTextCompare)
的隐含逻辑是:
TestString
包含String1
,后面跟0个或多个字符,后面跟String2
由于Instr
不支持通配符,请将测试分解为组件
Sub Demo()
Dim String1 As String
Dim String2 As String
Dim TestString As String
Dim Location As Integer
Dim i As Long, j As Long
String1 = "Hello"
String2 = "Goodbye"
TestString = "Hello and Goodbye"
i = InStr(1, TestString, String1, vbTextCompare)
If i > 0 Then
j = InStr(i + Len(String1), TestString, String2, vbTextCompare)
If j > 0 Then
'Do Something
End If
End If
End Sub
i
给出String1
的位置,j
给出String2
的位置,如果您的Do Something代码需要这些
注意,如果String2
是String
的子串,或者如果String2
发生在String1
之前和之后,则这里的另一个答案可能给出错误的结果