我有一个包含一堆常用术语的数组,用于表示该字段正在等待PO。然后我有一个循环向后通过一大列数据删除任何行,其中单元格中的值不匹配数组中的任何项。为此,我使用一个函数(我在网上找到)来测试数组中是否存在该值。
到目前为止一切都那么好,只要单元格中的值与数组中的值完全匹配即可。出现问题的地方是,如果一个单元格中包含一个常见术语的轻微变化(即。" TBC - 将在后面跟随"或者甚至只是" TBC"而不是" ; TBC"确切地说)
我需要一种方法来获取单元格中的值,并对数组中的值进行通配符搜索。我不会粘贴我的所有代码(现在它是一个中间发展的混乱),但是如果我们可以在下面开始工作,我可以应用它。
Sub TestFilterArray()
MyArray = Array("tbc", "awaiting po", "po to follow")
If IsInArray("tbc xyz", MyArray) = False Then
MsgBox "No! Item is not in the array"
Else
MsgBox "Yes! Item is in the array"
End If
End Sub
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
IsInArray = UBound(Filter(arr, stringToBeFound)) > -1
End Function
目前返回"不!..." for" tbc xyz"不在阵中,但我希望它回归"是的!..." for" tbc *"如果那是有道理的,那就在那里。
感谢任何帮助。
答案 0 :(得分:2)
Function IsInArray2(StringToBeFound As String, MyArray As Variant) As Boolean
IsInArray2 = False
For i = LBound(MyArray) To UBound(MyArray)
If "*" & MyArray(i) & "*" Like StringToBeFound Then IsInArray2 = True 'will match MyArray to any substring of StringToBeFound
Next
End Function
考虑到运行时注意事项,它变为
Function IsInArray2(StringToBeFound As String, MyArray As Variant) As Boolean
IsInArray2 = False
For i = LBound(MyArray) To UBound(MyArray)
If "*" & MyArray(i) & "*" Like StringToBeFound Then
IsInArray2 = True 'will match MyArray to any substring of StringToBeFound
Exit Function
End If
Next
End Function
谢谢你的评论。回过头来看,Like
声明是相反的,对不起。让我用一个案例和冗余匹配器以及一个测试来弥补它的重要性。
Function IsInArray2(stringToBeFound As String, MyArray As Variant) As Boolean
IsInArray2 = False
For i = LBound(MyArray) To UBound(MyArray)
If LCase(stringToBeFound) Like LCase("*" & Replace(MyArray(i), " ", "*") & "*") Then
IsInArray2 = True 'will match MyArray to any substring of StringToBeFound
Exit Function
End If
Next
End Function
Sub TestFilterArray()
MyArray = Array("coca cola gmbh", "awaiting po", "po to follow")
If IsInArray2("Coca Cola Deutschland GmbH", MyArray) = False Then
MsgBox "No! Item is not in the array"
Else
MsgBox "Yes! Item is in the array"
End If
End Sub
答案 1 :(得分:2)
此代码似乎可以满足您的需求:
Option Explicit
Sub TestFilterArray()
Dim MyArray As Variant
MyArray = Array("tbc", "awaiting po", "po to follow")
If arrMatch("tbc xyz", MyArray) = False Then
MsgBox "No! Item is not in the array"
Else
MsgBox "Yes! Item is in the array"
End If
End Sub
Function arrMatch(stringToSearch As String, Arr As Variant) As Boolean
Dim sS As String, sF As String
Dim I As Long
sS = " " & Trim(stringToSearch) & " "
For I = LBound(Arr) To UBound(Arr)
sF = "*" & Trim(Arr(I)) & "*"
If sS Like sF Then
arrMatch = True
Exit Function
End If
Next I
arrMatch = False
End Function