Excel 使用VBA计算筛选的行数

Excel 使用VBA计算筛选的行数,excel,vba,Excel,Vba,问题是RowCount在过滤后返回1,而不是可见的行 RowCount=单元格(Rows.Count,colIndex).结束(xlUp).特殊单元格(xlCellTypeVisible).行 Sub showEightmonth(ws, colName, colIndex) Dim RowCount As Integer ws.Activate MsgBox ws.Name RowCount = Cells(Rows.Count, colIndex).End(xlUp)

问题是RowCount在过滤后返回1,而不是可见的行

RowCount=单元格(Rows.Count,colIndex).结束(xlUp).特殊单元格(xlCellTypeVisible).行

Sub showEightmonth(ws, colName, colIndex)
Dim RowCount As Integer
    ws.Activate
    MsgBox ws.Name
    RowCount = Cells(Rows.Count, colIndex).End(xlUp).Row
    Set Rng = Range(colName & "1:" & colName & RowCount)

    If ws.AutoFilterMode = True Then
    ws.AutoFilter.ShowAllData
    End If

    Rng.Select
    Rng.NumberFormat = "mm/dd/yyyy hh:mm:ss"
    d = Format(DateAdd("m", -8, Date), "mm/dd/yyyy 07:00:00")
    Range(colName & "1").AutoFilter Field:=colIndex, Criteria1:="<" & d
    RowCount = Cells(Rows.Count, colIndex).End(xlUp).SpecialCells(xlCellTypeVisible).Row
    'Delete filtered row if RowCount > 1, as row 1 is the header row
    If RowCount > 1 Then
        delRow = colName & "2:" & colName & RowCount
        ActiveSheet.Range(delRow).SpecialCells(xlCellTypeVisible).EntireRow.Delete
    End If
    If ws.AutoFilterMode = True Then
    ws.AutoFilter.ShowAllData
    End If

End Sub
子显示八个月(ws、colName、colIndex)
将行计数设置为整数
ws.Activate
MsgBox ws.Name
RowCount=单元格(Rows.Count,colIndex).End(xlUp).Row
设置Rng=Range(colName&“1:”&colName&RowCount)
如果ws.AutoFilterMode=True,则
ws.AutoFilter.ShowAllData
如果结束
Rng.选择
Rng.NumberFormat=“mm/dd/yyyy hh:mm:ss”
d=格式(日期添加(“m”,-8,日期),“mm/dd/yyyy 07:00:00”)

范围(colName&“1”)。自动筛选字段:=colIndex,Criteria1:=“要计算应用筛选后可见的行,必须执行以下操作:

Sub countNonFiltered()

Dim sht As Worksheet
Dim colIndex As Long
Dim firstrow As Long
Dim RowCount As Long
Set sht = ThisWorkbook.Worksheets("worksheet name")
colIndex = 1    'let's assume you're interested in column A
firstrow = 2    'Let's assume your header is in row 1 and the data starts from row 2

With sht
    RowCount = .Range(.Cells(Rows.Count, 1).End(xlUp), .Cells(firstrow, colIndex)).SpecialCells(xlCellTypeVisible).Count
    Debug.Print RowCount
End With

End Sub
出于演示目的,上面的代码打印即时窗口中可见行的数量

请记住:

Cells(Rows.Count, colIndex).End(xlUp)
是一个仅包含一个单元格的区域。您需要的是一个区域,该区域包含属于应用筛选器后仍可见的行的所有单元格


还请记住,当您使用包含行或列索引的变量时,应将它们声明为
Long

要计算应用筛选器后可见的行,您必须执行以下操作:

Sub countNonFiltered()

Dim sht As Worksheet
Dim colIndex As Long
Dim firstrow As Long
Dim RowCount As Long
Set sht = ThisWorkbook.Worksheets("worksheet name")
colIndex = 1    'let's assume you're interested in column A
firstrow = 2    'Let's assume your header is in row 1 and the data starts from row 2

With sht
    RowCount = .Range(.Cells(Rows.Count, 1).End(xlUp), .Cells(firstrow, colIndex)).SpecialCells(xlCellTypeVisible).Count
    Debug.Print RowCount
End With

End Sub
出于演示目的,上面的代码打印即时窗口中可见行的数量

请记住:

Cells(Rows.Count, colIndex).End(xlUp)
是一个仅包含一个单元格的区域。您需要的是一个区域,该区域包含属于应用筛选器后仍可见的行的所有单元格

还要记住,当您使用包含行或列索引的变量时,它们应该声明为
Long