简体   繁体   English

Excel VBA - 在自动筛选中使用数组作为条件,而不是预期的结果

[英]Excel VBA - Use array as criteria in autofilter, not expected results

The ultimate goal of this procedure is to delete all rows in the "TestData" table that have a user which is listed in the "SysAccts" table (on the "Lists" worksheet). 此过程的最终目标是删除“TestData”表中具有“SysAccts”表(在“列表”工作表)中列出的用户的所有行。

I'm using autofilter to find those rows so I can select them and delete them. 我正在使用自动过滤器来查找这些行,以便我可以选择它们并删除它们。

This is my code: 这是我的代码:

Sub ClearSystemAccts()
    Dim wksData As Worksheet
    Dim objDataTable As ListObject
    Dim varSysAccts As Variant

    Set wksData = ActiveWorkbook.Sheets("Test Data")
    Set objDataTable = wksData.ListObjects("TestData")
    varSysAccts = Worksheets("Lists").Range("SystemAccts")

    With objDataTable.Range
        'turn off the autofilters as a reset
        .AutoFilter
        'set the autofilter with the criteria;
        .AutoFilter field:=2, Criteria1:=varSysAccts, Operator:=xlFilterValues
        'Delete the entire row for the visible cells; _
        'skips the header but also deletes the blank row below the table.
        .CurrentRegion.Offset(1).EntireRow.Delete
        'turn off autofilter
        .AutoFilter
    End With

End Sub

When I run the code, the autofilter display no rows in the table. 当我运行代码时,自动过滤器在表中不显示任何行。

I have validated that the varSysAccts variable is properly populated. 我已经验证varSysAccts变量已正确填充。

When I hover over the criteria in the Autofilter line, I get the following: 当我将鼠标悬停在Autofilter行中的条件上时,我得到以下内容: 输入不匹配通知

I think the problem is that when a table is read into an array, it is always a dynamic array. 我认为问题是当一个表被读入一个数组时,它总是一个动态数组。 But the table is only one column. 但该表只有一列。 How do I fix this? 我该如何解决?

EDITED : Per the comment below, I removed the array from the criteria. 编辑 :根据下面的评论,我从标准中删除了数组。 Now I don't get the type mismatch, but the filter still doesn't select any rows. 现在我没有得到类型不匹配,但过滤器仍然没有选择任何行。

Assuming that SystemAccts is a column, use 假设SystemAccts是一列,请使用

varSysAccts = Application.Transpose(Worksheets("Lists").Range("SystemAccts‌​")) 

That will make the array one-dimensional, rather than two-dimensional (rows x columns). 这将使数组成为一维的,而不是二维的(行x列)。

And then, because you already have an array, you only need to use Criteria1:=varSysAccts instead of Criteria1:=Array(varSysAccts) . 然后,因为你已经有了一个数组,你只需要使用Criteria1:=varSysAccts而不是Criteria1:=Array(varSysAccts)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM