I want to supply a number (ie. 4 which represents the 4th column – D) and then have a msgbox return the number of non blanks in that column
For example below there are 5 blanks in column D:
col A col B col C col D col E
------ ------- ---- ------- ------
gh
2h
34
code so far:
Sub Tester()
CountBlanks 4
End Sub
Sub CountBlanks(ByVal colNum)
columnLetter = ??
columnCount = ??
MsgBox "Count of column: " & columnLetter & " is " & columnCount
End Sub
Expected result:
"Count of column: D is 5"
The answer depends on what you actually want to count:
Most people are trying to achieve the first option which is a little tricky.
For counting blanks the specialcells function is the way to go. However as specialcells uses the sheets usedrange it can become unreliable as excel is known to keep track of the usedrange badly. So first we must call the usedrange function to reset it.
If you were after option 2 then it is just a case of getting the last cell in the column and counting with specialcells.
EDIT
Jmax, the code is actually correct. The call to reset the used range has to be on its own. On the next line when calling specialcells you don’t need to specify usedrange.
Its hard to explain but try this:
Comment out the ActiveSheet.UsedRange line. With your test data add a value to a cell further down the page from the table and run the code. It will return the count of blanks up to this newly added cell. Now delete the entire row of the cell you added and re-run the code. It will still return the same count because excel has not reset its inbuilt counter. Now uncomment the line Activesheet.Usedrange, run the code and you will get the correct result.