In Excel, I need to filter and display the COUNTIF & SUM of both the global range and the visible (or filtered) range.
I can already display the COUNTIF & SUM of the global range with the following code.
AtmCount = Application.WorksheetFunction.CountIf(Range("X3:X4533"), ">0")
AtmSum = Application.WorksheetFunction.Sum(Range("X3:X4533"))
I can also get the COUNT of the visible (or filtered) range as follows:
AtmCurrentCount = Range("X3:X4533").SpecialCells(xlCellTypeVisible).Count
However, this still leaves the SUM of visible (or filtered) range outstanding.
AtmCurrentSum = ???
I really stuck. Please, can somebody help me?
This will do what you want. Set visibleTotal to the appropriate data type for the total, and change the ws and rng objects to match what you have in your workbook.
Sub SumVisible()
Dim ws As Worksheet
Dim rng As Range
Dim visibleTotal As Long
Set ws = ThisWorkbook.Sheets("Sheet1")
Set rng = ws.Range("B1:B7")
ws.AutoFilterMode = False
rng.AutoFilter field:=1, Criteria1:=5
visibleTotal = Application.WorksheetFunction.Sum(rng.SpecialCells(xlCellTypeVisible))
' print to the immediate window
Debug.Print visibleTotal
End Sub
In case you only want to sum part of the filtered range (e.g. you filter on column A but want the sum of column B), see this question and answer: Copy/Paste/Calculate Visible Cells from One Column of a Filtered Table.
If one need to COUNT the number of visible items in a filtered list, then use the SUBTOTAL function, which automatically ignores rows that are hidden by a filter.
The SUBTOTAL function can perform calculations like COUNT, SUM, MAX, MIN, AVERAGE, PRODUCT and many more (See the table below). It automatically ignores items that are not visible in a filtered list or table. This makes it ideal for showing how many items are visible in a list, the subtotal of visible rows, etc. It also provide control rows hided manually manually.
The solution to your question would be to count the number of non-blank rows visible in Column A and Column B when a filter is active, use:
AtmCurrentSum = Application.WorksheetFunction.Subtotal(109, Range("$X$3:$X$4533"))
Points to remember when you apply SUBTOTAL formula:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With