Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA - Count Non Blank Cells Using Cell Reference

Tags:

excel

vba

In VBA, using Excel 2016, I am trying to count the number of non-blank cells for a given range but using only the cell integer reference. I've tried the following:

WB.Sheets(1).Range(Cells(2, X), _
Cells(2, Y)).Cells.SpecialCells(xlCellTypeConstants).count

Where X and Y are cell references for the columns. Please assist.

like image 668
nrcjea001 Avatar asked May 22 '26 19:05

nrcjea001


2 Answers

You can do this using the excel formula CountA as you're probably aware.

You can also use this in VBA using:

with WB.sheets(1)
    WorksheetFunction.CountA(Range(.Cells(2, X), .Cells(2, Y)))
end with
like image 168
Tom Avatar answered May 25 '26 17:05

Tom


Try this:

Range(WB.Sheets(1).Cells(2, X), _
WB.Sheets(1).Cells(2, Y)).Cells.SpecialCells(xlCellTypeConstants).count

You should add the workbook and worksheet before the cell and not before the range

like image 30
juanora Avatar answered May 25 '26 16:05

juanora



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!