繁体   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