我想按三个条件过滤,计算过滤的行数,在单元格N2中输出该计数,然后删除过滤的行。我不确定为什么下面的代码无法正常工作。
Sheets("Sheet1").Range("B4").Select
Sheets("Sheet1").Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select
Selection.AutoFilter Field:=8, Criteria1:=Array("A", "B", "C"), Operator:=xlFilterValues
Selection.Cell("N1").Select
ActiveCell.Value = Range(Cells(1, 1), Cells(Selection.SpecialCells(xlcelltypelast).Row, Selection.SpecialCells(xlCellTypeLastCell).Column)).Count
Selection.AutoFilter
答案 0 :(得分:0)
想象一下这些数据
xlLastCell
和xlcelltypelast
都不存在,您可能是想xlCellTypeLastCell
我建议激活Option Explicit
以避免这种错别字:在VBA编辑器中,转到< em>工具› 选项› Require Variable Declaration 。
过滤后的数据可能不是连续范围,而是划分为不同区域。
因此FilterRange.SpecialCells(xlCellTypeVisible).Rows.Count
仅会给您第一个区域的行数。因此,您必须遍历区域For Each iArea In FilterRange.SpecialCells(xlCellTypeVisible).Areas
并对.Rows.Count
求和才能得出总数。
Option Explicit
Sub FilterAndDelete()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet1")
Dim FilterRange As Range
Set FilterRange = ws.Range(ws.Range("B4"), ws.Range("B4").SpecialCells(xlCellTypeLastCell))
FilterRange.AutoFilter Field:=8, Criteria1:=Array("A", "B", "C"), Operator:=xlFilterValues
Dim RowCount As Long
Dim iArea As Range
For Each iArea In FilterRange.SpecialCells(xlCellTypeVisible).Areas
RowCount = RowCount + iArea.Rows.Count
Next iArea
ws.Range("N2").Value = RowCount - 1 'subtract header
'delete rows but keep header
Dim RowsToDelete As Range
On Error Resume Next 'next line throws error if filter is empty. Hide it.
Set RowsToDelete = FilterRange.Resize(RowSize:=FilterRange.Rows.Count - 1).Offset(RowOffset:=1).SpecialCells(xlCellTypeVisible)
'This Part FilterRange.Resize(RowSize:=FilterRange.Rows.Count - 1).Offset(RowOffset:=1) excludes the header from the FilterRange (we don't want to delete that).
On Error GoTo 0 'always re-activate error reporting!
If Not RowsToDelete Is Nothing Then
RowsToDelete.EntireRow.Delete
End If
FilterRange.AutoFilter
End Sub