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

时间:2016-07-08 13:29:17

标签: excel vba excel-vba

我下面有一些代码,应该检查一个值是否在数组中。

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由于某种原因包含单词ExamplesIsInArray会检测到两个数组都存在时vars1只存在IsInArray } array

我需要更改哪些内容才能使我的; This toggles the action toggle:=false F12:: ; If true is assigned to toggle, loop starts ; It also can assign false even when loop is running If (toggle := !toggle) SetTimer, loop, -1 return loop: ; Endless loop? Actually not, the value of toggle can be changed by ; another "thread" even when this loop is running while toggle { Click Sleep, 700 } return 功能完全匹配?

8 个答案:

答案 0 :(得分:19)

你可以像这样蛮力:

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"))

答案 1 :(得分:7)

此问题在此处提出: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

答案 2 :(得分:2)

在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

答案 3 :(得分:1)

虽然这本质上只是@Brad的回答,但我认为可能值得包括一个稍微修改的函数,如果数组中存在该函数,它将返回您要搜索的项的索引。如果该项不在数组中,它将返回-1

可以像检查“字符串中的功能” 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

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

test 2

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

答案 4 :(得分:0)

如果没有匹配项,则下面的函数将返回“ 0”,如果匹配则返回“正整数”:


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

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

答案 5 :(得分:0)

由于

,我想提供另一种应同时具有高性能和强大功能的变体

...

'-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

答案 6 :(得分:0)

我搜索了这个问题,当我看到答案时,我最终创建了一些在大多数情况下都适用的不同的东西(因为在大多数情况下,我倾向于使用比其他大多数东西更少的代码)。基本上将数组转换成一个字符串,其中数组元素由一些定界符分隔,然后将搜索值包装在定界符中并通过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))

答案 7 :(得分:-1)

您想检查范围(“A1”)中是否存在示例。值如果失败则检查示例是否正确?我认为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

End Sub