Sum visible cells

2019-09-08 07:34发布

After applied the advance filter, I sum only the visible cells by using the code below and it functions well. However, it shows error when there is no visible cell after the filter. Any idea on how to cover the error?

Sub sum ()
    Sheets("Sheet1").Select
    x = cells(Rows.Count, 8).End(xlUp).Row

    Sheets("Tax Invoice").Range("M55") = WorksheetFunction.Sum(Range("H7:H" & x).SpecialCells(xlCellTypeVisible))
End sub

1条回答
2楼-- · 2019-09-08 08:28

Count the number of visible rows before attempting to calculate the sum:

Option Explicit

Public Sub sumTaxInvRng()
    Dim x As Long, vRng As Range

    With Sheets("Sheet1")
        x = .Cells(.Rows.Count, 8).End(xlUp).Row
        Set vRng = .Range("H7:H" & x).SpecialCells(xlCellTypeVisible)
    End With

    If vRng.Count > vRng.Columns.Count Then
        Sheets("Tax Invoice").Range("M55") = WorksheetFunction.Sum(vRng)
    End If
End Sub

Also, you should not use a native function name for your functions: Sub sum()

查看更多
登录 后发表回答