使用 Excel VBA 检查字符串是不是在数组中或不包括通配符

Posted

技术标签:

【中文标题】使用 Excel VBA 检查字符串是不是在数组中或不包括通配符【英文标题】:Check if string is in array or not including wildcards with Excel VBA使用 Excel VBA 检查字符串是否在数组中或不包括通配符 【发布时间】:2017-03-29 09:48:41 【问题描述】:

我发现这个函数可以识别字符串是否在给定的数组中,但是它似乎无法处理通配符(或者至少不是我这样做的方式)。

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
  IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function

我对函数的使用:

Dim BannedWildcards() As Variant

BannedWildcards = Array("", "-", "?", 0, "na", "n/a", _
"*account*", "*hse*", "*defined*", "*applicable*", "*operation*", "*action*", "*manager*")

            Select Case True
            Case IsInArray(LCase(Sht_Tracker.Cells(RowCounter_CRCT, 17)), BannedWildcards) = True
                Arr_Dashboard_Current(10, ArrC_Dashboard_Current) = "#N/A"
            Case Else: Arr_Dashboard_Current(10, ArrC_Dashboard_Current) = Sht_Tracker.Cells(RowCounter_CRCT, 17)
            End Select

【问题讨论】:

这似乎就是你要找的东西:***.com/questions/30175061/wildcard-search-in-array 是和不是。我的一些字符串不是通配符,而另一些则是。您链接到的那个似乎无法区分它。话虽如此,我想最简单的方法是使用两个数组,一个带通配符,一个不带通配符 【参考方案1】:

或者类似的东西:

Function IsInArray2(StringToBeFound As String, MyArray As Variant) As Boolean
IsInArray2 = False
wildCard = "*"
If InStr(StringToBeFound, wildCard) > 0 Then
    For i = LBound(MyArray) To UBound(MyArray)
        If "*" & MyArray(i) & "*" Like StringToBeFound Then IsInArray2 =    True 'will match MyArray to any substring of StringToBeFound
    Next
Else
    For i = LBound(MyArray) To UBound(MyArray)
            If MyArray(i) == StringToBeFound Then IsInArray2 =  True 'will exactly match MyArray to StringToBeFound
    Next
End If
End Function

【讨论】:

【参考方案2】:

谢谢 SLWS。为了满足我的需要,我稍微修改了您引用的代码。这对我有用:

Function IsInArray(stringToBeFound As String, MyArray As Variant) As Boolean

    Dim i As Long
    Dim WildCard As String
    WildCard = "*"

    IsInArray = False

    For i = LBound(MyArray) To UBound(MyArray)
        If InStr(MyArray(i), WildCard) > 0 Then
            If LCase(stringToBeFound) Like LCase("*" & Replace(MyArray(i), " ", "*") & "*") Then
                IsInArray = True
                Exit Function
            End If
        Else
            If LCase(stringToBeFound) = LCase(MyArray(i)) Then
                IsInArray = True
                Exit Function
            End If
        End If
    Next
End Function

【讨论】:

以上是关于使用 Excel VBA 检查字符串是不是在数组中或不包括通配符的主要内容,如果未能解决你的问题,请参考以下文章

excel vba 数组中第1位字符为0,赋给单元格时如何将0保留?

Excel VBA 日期格式

Excel VBA 检查目录是不是存在错误

Excel vba 编译错误 - 参数不是可选的,

从 Excel VBA-检查访问表是不是存在/如果不存在,则创建/复制

excel vba检查命令按钮和复选框是不是存在