简体   繁体   English

如何使用可变标准进行自动过滤?

[英]How to autofilter with variable criteria?

I am trying to get an array or range of values and for each of them to filter all data in a sheet and copy it to a new sheet.我正在尝试获取一个数组或值范围,并为它们中的每一个过滤一张表中的所有数据并将其复制到一张新表中。

I have tried many ways.我尝试了很多方法。 I receive an error by the Autofilter method when I input a variable parameter instead of a string as 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

Error:错误:

run-time error "1004"运行时错误“1004”
Application-defined or object-defined error应用程序定义或对象定义的错误

The selection is a list of cells, each one containing a text, which should be the filtering criteria.选择是一个单元格列表,每个单元格都包含一个文本,这应该是过滤条件。

The column does not have a filter.该列没有过滤器。

This is what my workbook looks like.这就是我的工作簿的样子。 Column A is to be filtered while on column BI wrote the list of filtering criteria I would like to use. A 列将被过滤,而 BI 列写了我想使用的过滤条件列表。

excel工作簿

It is likely your issue is caused by the fact that you are changing the active sheet and relying on selection, and you should be using criteria1 , not criteria .您的问题很可能是由于您正在更改活动工作表并依赖于选择而引起的,您应该使用criteria1 ,而不是criteria Try avoiding selecting ranges that you don't need to:尽量避免选择您不需要的范围:

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