简体   繁体   English

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

[英]Check if string is in range Excel-VBA with Filter command

Im trying to check if a range of cells each have a value defined in another range 我正在尝试检查一个单元格区域是否每个单元格都有另一个范围内定义的值

This is my current code: 这是我当前的代码:

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

On the If UBound(filter(InstallationNameRange, cellA.Value)) < 0 Then I get the error "Run-time error '13': Type mismatch" and cannot find a solution for this. If UBound(filter(InstallationNameRange, cellA.Value)) < 0 Then我得到错误“运行时错误'13':类型不匹配”,并且无法找到解决方案。 Probably it is a very small fix. 可能是很小的修复。 Without this if-statement the code works 没有此if语句,代码将起作用

Open a new Excel and write the following: 打开一个新的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

Put some values in A1:B10 and D10:E20 and the addresses of the matching values would be printed in the immediate window. 将一些值放在A1:B10D10:E20中,匹配值的地址将显示在立即窗口中。

You can't use Filter on a 2-d range and any array created from a Range is 2-d even if it is a single row or column. 您不能在2-d范围内使用Filter ,并且从Range创建的任何数组都是2-d,即使它是单行或单列。

You can use the 'double Transpose trick` per this question . 您可以针对每个问题使用“双重Transpose技巧”。 Note the highly up-voted answer, not the accepted one. 注意投票率很高的答案,而不是公认的答案。

Eg: 例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM