虽然substring有效,但Excel VBA InStr返回0

时间:2017-09-21 14:38:16

标签: excel vba excel-vba

在此代码中,我试图检查用户输入的输入(txtList)是否可以在数据列表(txtList)中找到。下面的代码返回0(虽然" John Ho"" Ho Tee Nee,John"是完全相同的人,但是找不到子字符串。有人可以请教我如何解决这个问题吗? / p>

'code returns 0 (substring not found)
Dim txtList As String, txtInput As String
txtList = "Ho Tee Nee, John"
txtInput = "John Ho"
Debug.Print InStr(1, txtList, txtInput, vbTextCompare)

1 个答案:

答案 0 :(得分:7)

拆分搜索条件并查找每个部分。

Dim i As Long, txtList As String, txtInput As Variant
txtList = Chr(32) & "Ho Tee Nee, John" & Chr(32)
txtInput = Split("John Ho", Chr(32))

For i = LBound(txtInput) To UBound(txtInput)
    If Not CBool(InStr(1, txtList, Chr(32) & txtInput(i) & Chr(32), vbTextCompare)) Then Exit For
Next i

If i > UBound(txtInput) Then
    Debug.Print "all parts match"
Else
    Debug.Print "incomplete match"
End If

这是一个不区分大小写的搜索。对于区分大小写的搜索,请将vbTextCompare更改为vbBinaryCompare。