簡體   English   中英

如何使用可變標准進行自動過濾?

[英]How to autofilter with variable criteria?

我正在嘗試獲取一個數組或值范圍,並為它們中的每一個過濾一張表中的所有數據並將其復制到一張新表中。

我嘗試了很多方法。 當我輸入變量參數而不是字符串作為條件時,我通過 Autofilter 方法收到錯誤。

Sub Macro1()
    Dim Cll As Range
    For Each Cll In Selection
        Columns("A:A").Select
        Selection.AutoFilter Field:=1, Criteria:=Cll.Value  '‹- here I get the error
        Cells.Select
        Selection.Copy
        Sheets.Add After:=ActiveSheet
        ActiveSheet.Paste
    Next Cll  
End Sub

錯誤:

運行時錯誤“1004”
應用程序定義或對象定義的錯誤

選擇是一個單元格列表,每個單元格都包含一個文本,這應該是過濾條件。

該列沒有過濾器。

這就是我的工作簿的樣子。 A 列將被過濾,而 BI 列寫了我想使用的過濾條件列表。

excel工作簿

您的問題很可能是由於您正在更改活動工作表並依賴於選擇而引起的,您應該使用criteria1 ,而不是criteria 盡量避免選擇您不需要的范圍:

Sub Macro1()
    Dim criteriaRange As Range
    Set criteriaRange = Selection
    Dim filterRange As Range
    With ActiveSheet
        .AutoFilterMode = False
        Set filterRange = .Range("A4:A" & .Cells(.Rows.Count, "A").End(xlUp).Row)
    End With
    Dim Cll As Range
    For Each Cll In criteriaRange.Cells
        filterRange.AutoFilter Field:=1, Criteria1:=Cll.Value  '‹- here I get the error
        filterRange.Copy
        Sheets.Add After:=ActiveSheet
        ActiveSheet.Paste
    Next Cll
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM