To count non-blank cells in Excel using VBA, use the Application.WorksheetFunction.CountIf method with a criteria of "<>", or use CountA for a simpler direct count. This avoids blank cells, including those with empty strings returned by formulas. Ensure your range is properly defined and your sheet is not protected (or unprotect it first in code).
What You'll Need
- Microsoft Excel installed (Excel 2010 or later)
- Basic familiarity with the VBA editor (Alt + F11)
- A worksheet with data in a contiguous or non-contiguous range
- Optional: A reference to the Microsoft Scripting Runtime if using Dictionary objects (not required for basic CountIf/CountA)
Step-by-Step
- Open Excel and press Alt + F11 to open the Visual Basic for Applications (VBA) editor.
- In the VBA editor, go to Insert > Module to create a new standard module. This is where your macro code will live.
- Declare a subroutine. Type or paste the following starter code:
This defines the macro name. You can rename it (e.g.,Sub CountNonBlankCells()CountNotBlanks), but avoid spaces or special characters. - Define the range you want to evaluate. For example, to check cells A1 through A100 on the active sheet:
ReplaceDim rng As Range Set rng = ThisWorkbook.Sheets("Sheet1").Range("A1:A100")"Sheet1"with your actual sheet name, and adjust the range as needed. UsingThisWorkbookensures you target the workbook containing the code, not the active one. - Use
CountIfwith a non-blank criteria. Paste this line after theSet rngline:
TheDim countResult As Long countResult = Application.WorksheetFunction.CountIf(rng, "<>")"<>"means "not equal to blank"—this counts all cells that contain any value (text, number, date, error) but excludes truly empty cells and cells with empty strings ("") only if the cell is physically blank. Note:CountIfwith"<>"does count cells containing a formula that returns an empty string as non-blank—this is a key limitation to remember. - For a more reliable count of truly non-empty cells (excluding formulas returning
""), useCountAinstead:countResult = Application.WorksheetFunction.CountA(rng)CountAcounts any cell that is not empty—including cells with spaces, zeros, or formulas returning"". To exclude only zero-length strings, you would need a loop (see Tips). - Output the result. To display it in a message box:
Or write it to a cell (e.g., B1):MsgBox "Non-blank cells: " & countResult, vbInformation, "Result"
This writes to the cell one column to the right of the start of your range (A1 → B1).rng.Offset(0, 1).Cells(1, 1).Value = countResult - Close the subroutine:
End Sub - Run the macro. Press F5 inside the VBA editor, or return to Excel and press Alt + F8, select
CountNonBlankCells, then click Run.
Common Mistakes
- Using
CountIf(rng, "")to find non-blanks: This counts blank cells, the opposite of what you want. Always use"<>"orCountA. - Ignoring truly empty strings:
CountIfwith"<>"counts cells where a formula returns""as non-blank because the cell is not physically empty. UseCountAfor a broader count, or a loop to filter. - Hard-coding sheet names: If the sheet is renamed, your code breaks. Use
ActiveSheetonly if you’re certain the correct sheet is active, or reference by index (e.g.,Sheets(1)). - Unprotected sheets: If the sheet is protected,
Set rngor writing output may fail. Unprotect first in code:Sheets("Sheet1").Unprotect Password:="mypassword"(if a password is set). - Range scope errors: Using
Range("A1:A100")without specifying a worksheet defaults toActiveWorkbook.ActiveSheet, which may not be your intended sheet.
Tips
- Use
CountAfor simplicity: If you need to count any non-empty cell (including those with formulas returning""),CountAis faster and cleaner thanCountIfwith"<>". - Exclude zero-length strings: To exclude cells where a formula returns
"", loop through each cell and checkLen(Trim(cell.Value)) > 0:
This trims spaces and checks if any visible characters remain.Dim cell As Range Dim trueNonBlank As Long trueNonBlank = 0 For Each cell In rng If Len(Trim(cell.Value)) > 0 Then trueNonBlank = trueNonBlank + 1 Next cell - Multiple ranges: Combine non-contiguous ranges using
Application.Union:
Then applySet rng = Union(Range("A1:A10"), Range("C1:C10"))CountAor the loop above. - Error handling: Wrap your code in
On Error GoTo ErrHandlerto catch issues like missing sheets or protected ranges gracefully.
Troubleshooting
- Macro doesn’t run: Check if macros are enabled. In Excel, go to File > Options > Trust Center > Trust Center Settings > Macro Settings and select Enable all macros (for testing only—disable later for security).
- Incorrect count: Verify if your range includes header rows or hidden rows.
CountAcounts hidden cells too. To count only visible cells, useSubtotal(103, rng)(103 isCOUNTAfor visible cells only). - Run-time error '1004': This often means the sheet name is wrong or the range is invalid. Double-check the sheet name spelling and ensure the sheet exists. Also, confirm the workbook is saved in a macro-enabled format (
.xlsm). - Count includes empty-looking cells: Some cells may contain spaces or non-printing characters (e.g.,
CHAR(160)). UseTrimin a helper column or loop (as in the Tips section) to handle this. - Protected sheet blocks code: If your sheet is protected, add
.Unprotectbefore operations and.Protectafterward. If a password is set, include it in the.Unprotectcall.
Frequently Asked Questions
Does CountIf with "<>" count cells with formulas returning ""?
Yes.CountIf(range, "<>") counts cells that are not physically empty—even if a formula returns "". To exclude these, use CountA or a loop with Len(Trim(...)) > 0.
Can I count non-blank cells across multiple sheets?
Not with a singleCountIf call. You must loop through each sheet’s range and sum the counts, or use Application.Union to combine ranges across sheets (if they’re identical and contiguous) before applying CountA.
What’s the difference between CountIf and CountA?
CountIf counts cells that meet a specific condition (e.g., "<>" for non-blank), while CountA counts all non-empty cells regardless of content. CountA is essentially a built-in, optimized version for this case.
Why does my count include cells that look empty?
Cells may contain invisible characters (like spaces, line breaks, or non-breaking spaces), or formulas returning"". Use the Len(Trim(cell.Value)) > 0 loop to exclude such cases.
Can I use this in a UserForm or worksheet event?
Yes. Place the same logic inside a UserForm button’sClick event or a worksheet event (e.g., Worksheet_Activate). Just ensure the range references are correct and protected sheets are handled.