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

  1. Open Excel and press Alt + F11 to open the Visual Basic for Applications (VBA) editor.
  2. In the VBA editor, go to Insert > Module to create a new standard module. This is where your macro code will live.
  3. Declare a subroutine. Type or paste the following starter code:
    Sub CountNonBlankCells()
    This defines the macro name. You can rename it (e.g., CountNotBlanks), but avoid spaces or special characters.
  4. Define the range you want to evaluate. For example, to check cells A1 through A100 on the active sheet:
        Dim rng As Range
        Set rng = ThisWorkbook.Sheets("Sheet1").Range("A1:A100")
    Replace "Sheet1" with your actual sheet name, and adjust the range as needed. Using ThisWorkbook ensures you target the workbook containing the code, not the active one.
  5. Use CountIf with a non-blank criteria. Paste this line after the Set rng line:
        Dim countResult As Long
        countResult = Application.WorksheetFunction.CountIf(rng, "<>")
    The "<>" 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: CountIf with "<>" does count cells containing a formula that returns an empty string as non-blank—this is a key limitation to remember.
  6. For a more reliable count of truly non-empty cells (excluding formulas returning ""), use CountA instead:
        countResult = Application.WorksheetFunction.CountA(rng)
    CountA counts 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).
  7. Output the result. To display it in a message box:
        MsgBox "Non-blank cells: " & countResult, vbInformation, "Result"
    Or write it to a cell (e.g., B1):
        rng.Offset(0, 1).Cells(1, 1).Value = countResult
    This writes to the cell one column to the right of the start of your range (A1 → B1).
  8. Close the subroutine:
    End Sub
  9. 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 "<>" or CountA.
  • Ignoring truly empty strings: CountIf with "<>" counts cells where a formula returns "" as non-blank because the cell is not physically empty. Use CountA for a broader count, or a loop to filter.
  • Hard-coding sheet names: If the sheet is renamed, your code breaks. Use ActiveSheet only 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 rng or 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 to ActiveWorkbook.ActiveSheet, which may not be your intended sheet.

Tips

  • Use CountA for simplicity: If you need to count any non-empty cell (including those with formulas returning ""), CountA is faster and cleaner than CountIf with "<>".
  • Exclude zero-length strings: To exclude cells where a formula returns "", loop through each cell and check Len(Trim(cell.Value)) > 0:
        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
    This trims spaces and checks if any visible characters remain.
  • Multiple ranges: Combine non-contiguous ranges using Application.Union:
        Set rng = Union(Range("A1:A10"), Range("C1:C10"))
    Then apply CountA or the loop above.
  • Error handling: Wrap your code in On Error GoTo ErrHandler to 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. CountA counts hidden cells too. To count only visible cells, use Subtotal(103, rng) (103 is COUNTA for 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)). Use Trim in a helper column or loop (as in the Tips section) to handle this.
  • Protected sheet blocks code: If your sheet is protected, add .Unprotect before operations and .Protect afterward. If a password is set, include it in the .Unprotect call.

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 single CountIf 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’s Click event or a worksheet event (e.g., Worksheet_Activate). Just ensure the range references are correct and protected sheets are handled.

Does this work in Excel Online or Excel for Mac?

VBA macros are supported in Excel for Mac and Excel Online, but some features may behave differently. In Excel Online, macros are limited to those in the workbook and require the desktop app for full editing. Always test in your environment.