使用Excel VBA检查值是否在数组中

cngwdvgl  于 2023-01-31  发布在  其他
关注(0)|答案(8)|浏览(684)

我有下面的一些代码,这是应该检查,如果一个值是在一个数组或没有.

Sub test()
    vars1 = Array("Examples")
    vars2 = Array("Example")
    If IsInArray(Range("A1").Value, vars1) Then
        x = 1
    End If

    If IsInArray(Range("A1").Value, vars2) Then
        x = 1
    End If
End Sub

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

如果单元A1由于某种原因包含字Examples,则两个IsInArray都检测到它存在于两个数组中,而实际上它应该只发现它存在于vars1数组中
要使IsInArray函数完全匹配,需要做哪些更改?

jgzswidk

jgzswidk1#

你可以像这样强制执行:

Public Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
    Dim i
    For i = LBound(arr) To UBound(arr)
        If arr(i) = stringToBeFound Then
            IsInArray = True
            Exit Function
        End If
    Next i
    IsInArray = False

End Function

使用类似

IsInArray("example", Array("example", "someother text", "more things", "and another"))
r6vfmomb

r6vfmomb2#

这个问题是在这里提出的:VBA Arrays - Check strict (not approximative) match

Sub test()
    vars1 = Array("Examples")
    vars2 = Array("Example")
    If IsInArray(Range("A1").value, vars1) Then
        x = 1
    End If

    If IsInArray(Range("A1").value, vars2) Then
        x = 1
    End If
End Sub

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
    IsInArray = Not IsError(Application.Match(stringToBeFound, arr, 0))
End Function
cbeh67ev

cbeh67ev3#

我搜索了这个问题,当我看到答案时,我最终创建了一些不同的东西(因为大多数时候我喜欢更少的代码),这些东西应该在绝大多数情况下都能工作。基本上,把数组变成一个字符串,数组元素由一些分隔符分隔,然后把搜索值 Package 在分隔符中,并通过instr传递。

Function is_in_array(value As String, test_array) As Boolean
    If Not (IsArray(test_array)) Then Exit Function
    If InStr(1, "'" & Join(test_array, "'") & "'", "'" & value & "'") > 0 _
        Then is_in_array = True
End Function

你可以这样执行这个函数:

test = is_in_array(1, array(1, 2, 3))
mbskvtky

mbskvtky4#

使用excel VBA中的Match()函数检查数组中是否存在该值。

Sub test()
    Dim x As Long

    vars1 = Array("Abc", "Xyz", "Examples")
    vars2 = Array("Def", "IJK", "MNO")

    If IsNumeric(Application.Match(Range("A1").Value, vars1, 0)) Then
        x = 1
    ElseIf IsNumeric(Application.Match(Range("A1").Value, vars2, 0)) Then
        x = 1
    End If

    MsgBox x
End Sub
jutyujz0

jutyujz05#

如果不匹配,则以下函数返回“0”,如果匹配,则返回“正整数”:

Function IsInArray(stringToBeFound As String, arr As Variant) As Integer 
    IsInArray = InStr(Join(arr, ""), stringToBeFound) 
End Function

注意:函数首先使用'Join'将整个数组内容连接到一个字符串(不确定join方法是否使用内部循环),然后使用InStr检查该字符串中的匹配项。

zfciruhq

zfciruhq6#

虽然这基本上又是@布拉德的回答,但我认为可能值得包含一个稍微修改的函数,如果数组中存在要搜索的项,它将返回该项的索引;如果该项不在数组中,它将返回-1
这个函数的输出可以像“in string”函数If InStr(...) > 0 Then一样进行检查,所以我在它下面做了一个小测试函数作为例子。

Option Explicit

Public Function IsInArrayIndex(stringToFind As String, arr As Variant) As Long

    IsInArrayIndex = -1

    Dim i As Long
    For i = LBound(arr, 1) To UBound(arr, 1)
        If arr(i) = stringToFind Then
            IsInArrayIndex = i
            Exit Function
        End If
    Next i

End Function

Sub test()

    Dim fruitArray As Variant
    fruitArray = Array("orange", "apple", "banana", "berry")

    Dim result As Long
    result = IsInArrayIndex("apple", fruitArray)

    If result >= 0 Then
        Debug.Print chr(34) & fruitArray(result) & chr(34) & " exists in array at index " & result
    Else
        Debug.Print "does not exist in array"
    End If

End Sub

然后我做得有点过火,充实了一个二维数组,因为当你generate an array based on a range的时候,它通常是这样的。
它返回一个只有两个值的一维变量数组,数组的两个索引用作输入(假设找到值),如果没有找到值,它返回一个(-1, -1)数组。

Option Explicit

Public Function IsInArray2DIndex(stringToFind As String, arr As Variant) As Variant

    IsInArray2DIndex= Array(-1, -1)

    Dim i As Long
    Dim j As Long

    For i = LBound(arr, 1) To UBound(arr, 1)
        For j = LBound(arr, 2) To UBound(arr, 2)
            If arr(i, j) = stringToFind Then
                IsInArray2DIndex= Array(i, j)
                Exit Function
            End If
        Next j
    Next i

End Function

下面是我为测试设置的数据的图片,后面是测试:

Sub test2()

    Dim fruitArray2D As Variant
    fruitArray2D = sheets("Sheet1").Range("A1:B2").value

    Dim result As Variant
    result = IsInArray2DIndex("apple", fruitArray2D)

    If result(0) >= 0 And result(1) >= 0 Then
        Debug.Print chr(34) & fruitArray2D(result(0), result(1)) & chr(34) & " exists in array at row: " & result(0) & ", col: " & result(1)
    Else
        Debug.Print "does not exist in array"
    End If

End Sub
zaqlnxep

zaqlnxep7#

我想提供另一个变体,它应该是高性能和强大的,因为

  • 它不使用有时较慢的Match
    *支持StringIntegerBooleannot String -only
    *返回搜索项目的 * 索引
    支持 * 第n次出现

...

'-1 if not found
'https://stackoverflow.com/a/56327647/1915920
Public Function IsInArray( _
  item As Variant, _
  arr As Variant, _
  Optional nthOccurrence As Long = 1 _
  ) As Long

    IsInArray = -1

    Dim i As Long:  For i = LBound(arr, 1) To UBound(arr, 1)
        If arr(i) = item Then
            If nthOccurrence > 1 Then
                nthOccurrence = nthOccurrence - 1
                GoTo continue
            End If
            IsInArray = i
            Exit Function
        End If
continue:
    Next i

End Function

像这样使用它:

Sub testInt()
  Debug.Print IsInArray(2, Array(1, 2, 3))  '=> 1
End Sub

Sub testString1()
  Debug.Print IsInArray("b", Array("a", "b", "c", "a"))  '=> 1
End Sub

Sub testString2()
  Debug.Print IsInArray("b", Array("a", "b", "c", "b"), 2)  '=> 3
End Sub

Sub testBool1()
  Debug.Print IsInArray(False, Array(True, False, True))  '=> 1
End Sub

Sub testBool2()
  Debug.Print IsInArray(True, Array(True, False, True), 2)  '=> 2
End Sub
rkue9o1l

rkue9o1l8#

你想检查Examples是否存在于Range("A1"). Value如果失败,那么检查Examples对吗?我认为mycode将工作完美。请检查。

Sub test()
Dim string1 As String, string2 As String
string1 = "Examples"
string2 = "Example"
If InStr(1, Range("A1").Value, string1) > 0 Then
    x = 1
ElseIf InStr(1, Range("A1").Value, string2) > 0 Then
    x = 2
End If

末端子组件

相关问题