【问题标题】:EXCEL VBA compare cell values to an ArrayEXCEL VBA 将单元格值与数组进行比较
【发布时间】:2017-09-05 07:31:43
【问题描述】:

我以这篇文章为灵感: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

【问题讨论】:

    标签: arrays excel vba compare range


    【解决方案1】:

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

    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
    

    【讨论】:

    • 您好 JensS。所以我只是用你的替换了我的“函数 IsInArray”并保留了 Sub Check(),但我仍然得到这个“类型不匹配”并出现运行时错误 13?
    • 只要去掉 Dim arr() As String 这行,然后数组声明为一个变体
    • 好的,现在它可以进一步工作,直到函数中的“If Str(Element) = Str(VarToBeFound) Then”行,但随后我再次收到“类型不匹配”,运行时错误13
    • 好吧,如果你的数据已经包含字符串,你可以写 Element = VarToBeFound - 但这取决于你要比较的数据类型。
    • ...这正是我需要做的!现在它完美地工作了。非常感谢您的快速帮助,非常感谢。
    猜你喜欢
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多