使用Filter命令检查字符串是否在Excel-VBA范围内

时间:2017-10-05 09:59:19

标签: excel vba excel-vba

我试图检查一系列单元格是否都有另一个范围内定义的值

这是我目前的代码:

Sub CheckInstallationName()

    Dim LastRow As Long

    With Worksheets(2)
        LastRow = .Cells(.Rows.Count, Worksheets(1).Cells(4, 3).Value).End(xlUp).Row
    End With

    Dim rngA As Range
    Set rngA = Range(Worksheets(1).Cells(4, 3).Value & "4:" & Worksheets(1).Cells(4, 3).Value & LastRow)

    Dim cellA As Range
    Dim InstallationNameRange As Variant

    InstallationNameRange = Worksheets(1).Range("B16:B32").Value

    For Each cellA In rngA
        If UBound(Filter(InstallationNameRange, cellA.Value)) < 0 Then
            'Some code
        End If
    Next cellA

End Sub

If UBound(filter(InstallationNameRange, cellA.Value)) < 0 Then我收到错误“运行时错误'13':输入不匹配”,但无法找到解决方法。可能这是一个非常小的修复。没有这个if语句,代码就可以了

2 个答案:

答案 0 :(得分:1)

打开一个新的Excel并编写以下内容:

Public Sub CheckRangeInRange()

    Dim rngA        As Range
    Dim rngB        As Range
    Dim rngCellA    As Range
    Dim rngCellB    As Range
    Dim blnError    As Boolean

    Set rngA = Worksheets(1).Range("A1:B10")
    Set rngB = Worksheets(1).Range("D10:E20")

    rngA.Interior.Color = vbYellow
    rngB.Interior.Color = vbRed

    For Each rngCellA In rngA
        blnError = True
        For Each rngCellB In rngB
            If rngCellA = rngCellB Then
                blnError = False
            End If
        Next rngCellB
        If blnError Then Debug.Print "Display Error here!"
    Next rngCellA

End Sub

A1:B10D10:E20中添加一些值,匹配值的地址将在即时窗口中打印。

答案 1 :(得分:1)

您不能在2-d范围内使用Filter,并且从Range创建的任何数组都是2-d,即使它是单行或列也是如此。

您可以按照question使用'double Transpose技巧。请注意高度投票的答案,而不是被接受的答案。

E.g:

Option Explicit

Sub Test()

    Dim rng As Range
    Set rng = Sheet2.Range("C20:E20") 'a, b, c

    ' use the double transpose trick to convert 2-d array to 1-d array
    Dim arr As Variant
    arr = Application.WorksheetFunction.Transpose( _
        Application.WorksheetFunction.Transpose(rng.Value))

    ' now Filter will work
    Dim out As Variant
    out = Filter(arr, "a")

    Debug.Print out(0)

End Sub