簡體   English   中英

使用篩選器命令檢查字符串是否在Excel-VBA范圍內

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

我正在嘗試檢查一個單元格區域是否每個單元格都有另一個范圍內定義的值

這是我當前的代碼:

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語句,代碼將起作用

打開一個新的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中,匹配值的地址將顯示在立即窗口中。

您不能在2-d范圍內使用Filter ,並且從Range創建的任何數組都是2-d,即使它是單行或單列。

您可以針對每個問題使用“雙重Transpose技巧”。 注意投票率很高的答案,而不是公認的答案。

例如:

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