EXCEL VBA将单元格值与数组进行比较

时间:2017-09-05 07:31:43

标签: arrays excel vba compare range

我用这篇文章作为灵感:How to find if an array contains a string

希望你们能帮助我:

我想在Excel工作表中逐个单元格地遍历列(范围)并查找单元格值是否也在从excel范围归档的数组中,但由于某种原因我得到了一个类型不匹配错误。我猜,它与数组的声明作为变体有关,但将其更改为字符串也无济于事。

非常感谢,非常感谢任何帮助

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

Sub Check()

Dim cell As Range
Dim arr() As String
arr = Range("I2:I3").Value

For Each cell In Range("D2:D15")

    If IsInArray(CStr(cell.Value), arr) Then
     cell.Interior.Color = RGB(0, 176, 80)
    Else
     cell.Interior.Color = RGB(0, 0, 0)
    End If

Next cell
End Sub

1 个答案:

答案 0 :(得分:0)

过滤器仅适用于字符串 - 而不是对象;一个简单的解决方案是使用它:

Function IsInArray(ByVal VarToBeFound As Variant, ByVal Arr As Variant) As Boolean
    Dim Element As Variant
    For Each Element In Arr
        If Element = VarToBeFound Then
            IsInArray = True
            Exit Function
        End If
    Next Element

    IsInArray = False
End Function