使用Excel VBA Autofilter时如何删除空白行

我已经写了一个macros来search工作簿,并将自动筛选器应用于任何有名为“Code”的列表对象。 但是,当我应用筛选器时,它不会筛选出空白行。 任何想法如何我可以过滤掉这些?

以下是应用filter的代码:

Public Sub ApplyFilter(filter As Variant) Dim wb As Workbook Dim ws As Worksheet Dim lo As ListObject Set wb = ActiveWorkbook ' Loop through each sheet in the workbook For Each ws In wb.Sheets ' Find any listobjects within the sheet For Each lo In ws.ListObjects Dim r As Integer ' Find the column named Code and filter on this column r = lo.Range.Rows(1).Find("Code").Column ' Clear any existing filter lo.Range.AutoFilter Field:=r ' If the filter code is not "All Categories", 999, apply the filter If filter(0) <> 999 Then lo.Range.AutoFilter Field:=r, Criteria1:=filter, Operator:=xlFilterValues End If Next Next End Sub 

传入的filter是一个数组,它可能只有一个标准,或许多。 我也尝试添加criteria2:=“”,但是这并没有改变任何东西。

如果您有任何想法,请告诉我。 谢谢!

以下是其他相关的代码:

 Public Sub FilterInvoice(filter As Range) Me.ApplyFilter Me.BuildFilter(filter) End Sub Public Function BuildFilter(filter As Range) As Variant Dim r As Range Dim arFilter() As String ' Get the cell of the current category Set r = Range("Categories").Find(filter.Value) ' Set the initial filter value to the category id ReDim Preserve arFilter(1) arFilter(0) = r.Offset(0, -1).Value ' Find any child categories, add child id's to filter array For c = 1 To Application.CountIf(Range("Categories").Columns(3), arFilter(0)) Dim PrevChild As Range ' Expand the filter array ReDim Preserve arFilter(c + 1) If c = 1 Then Set PrevChild = Range("Categories").Columns(3).Find(arFilter(0)) Else ' If it is not the first time through the loop, look for the next child after PrevChild Set PrevChild = Range("Categories").Columns(3).Find(arFilter(0), PrevChild) End If ' Offset the found child to get its code, add it to the filter array arFilter(c) = PrevChild.Offset(, -2) Next ' Add "<>" and "<900" to the criteria list to hide blank rows 'ReDim Preserve arFilter(UBound(arFilter) + 2) 'arFilter(UBound(arFilter) - 1) = "<>" 'arFilter(UBound(arFilter)) = "<900" 'Return the filter array BuildFilter = arFilter End Function 

如果您使用数组过滤多个条件,则不包括“=”,自动筛选器应过滤空白。 例如,这不会过滤空白:

 Criteria1:=Array("test", "2", "3", "4", "=") 

如果没有,您可能需要使用特殊单元(xlcelltypeblanks)手动隐藏它们。

编辑:

好吧,我想我可能会用我的第一个解决scheme把你弄糊涂了。 我已经删除它。

现在我可以看到你的代码,我想可能发生的事情是,当你循环遍历范围并添加你的标准时,你可能会添加一个空白单元格。 逐步循环一次,确保事实并非如此。 你可以添加这个来显示filter,并确保它不包含空格:

Debug.Print Join(arfilter,“,”)