【问题标题】:Filter column based on array from another sheet基于另一个工作表中的数组过滤列
【发布时间】:2017-12-26 01:10:26
【问题描述】:

我有三张名为:“Dane magazyn”、“Sheet3”和“Dostawcy”的工作表。 我希望我的 Excel 做的是:

1) 过滤掉 col 中的 #N/A 值。工作表“Dane magazyn”上的 J。过滤后应保留的所有值都存储在工作表“Dostawcy”上的 Col.E 中 - 21 个条目,但将来会更多。

2) 选择过滤后剩余的数据,复制到“Sheet3”

到目前为止,这是我的代码:

Sub filtruj()
Dim i As Long, arr As Variant, LastRow As Long
Sheets("Dostawcy").Select
With ActiveSheet
    LastRow = .Cells(.Rows.Count, "E").End(xlUp).Row
End With
arr = Sheets("Dostawcy").Range("E2:E" & LastRow).Value
Sheets("Dane magazyn").Select
With ActiveSheet
**.Columns("J").AutoFilter Field:=1, Criteria1:=arr, Operator:=xlFilterValues** <---- here I get error
End With

其余代码...

我得到的错误信息是: “运行时错误‘1004’:

Range 类的 AutoFilter 方法失败"

我检查过的网站(未全部列出)

Using string array as criteria in VBA autofilter

VBA assign a range to an Array from different sheet

Fastest way to read a column of numbers into an array

提前致谢

【问题讨论】:

    标签: arrays excel vba filter


    【解决方案1】:

    这是工作代码:

    Dim rng, rngToFilter As Range
    Dim i As Integer: i = 1
    'set you range to area with values to compare against
    'if you can, specify here exact range instead of whole column, it can increase efficiency
    Set rng = Sheets("Dostawcy").Range("E:E")
    
    'set range to be filtered out, don't specify here whole column,
    'in following loop it can result in overflow error
    Set rngToFilter = Sheets("Dane magazyn").Range("J1:J100")
    'here we will iterate through all cells within the searched range,
    'for every cell we will try to find it's value within the other range,
    'if it succeeds, so it's not Nothing, then we copy it to Sheet3
    For Each cell In rngToFilter
        'if any cell causes the error, we will skip one iteration
        On Error GoTo ErrorHandler:
        If Not rng.Find(cell.Value) Is Nothing Then
            Sheets("Sheet3").Cells(i, 1).Value = cell.Value
            i = i + 1
        End If
        ErrorHandler:
    Next cell
    

    除非必须,否则不要使用Select,它会降低程序的效率。

    【讨论】:

    • '对于 rngToFilter 中的每个单元格,如果不是,则 rngFind(cell.Value) 什么都没有,那么
    • 尝试更正的代码。你是对的复制。尝试扩展此行为,使其满足您的要求。
    • Set rngToFilter = Sheets("Dane magazynu").Range("J1:J100000")
    • 您没有指定的那么多行...我认为J100 就足够了。
    • 未来它可能会达到 20k 行,但无论行数(100 或 100000)如何都会发生错误
    猜你喜欢
    • 1970-01-01
    • 2016-03-28
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    • 2018-04-04
    • 1970-01-01
    相关资源
    最近更新 更多