Home » excel » excel – VBA Count Values in Array

excel – VBA Count Values in Array

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’ve read the post on this VBA problem, but my VBA script is still not working.

Public Sub Test()

Dim arrNames As Variant                     'Declare array named "arrNames"
arrNames = Sheet1.Range("F2:F1000")         'Array filled with column F
intN = Application.CountIf(arrNames, "*")   'does not work intent: count cells w/info
'intN = Application.CountA(arrNames)        'works but MsgBox displays value of 999
MsgBox (intN)

End Sub

How do I get the number of cells in my array containing any value?

EDITED version after help

Public Sub Test()

Dim arrNames As Variant                       'Declare array named "arrNames"
Dim i As Long

arrNames = Sheet1.Range("F2:F1000")           'Array filled with column F

For i = LBound(arrNames) To UBound(arrNames)
    If (arrNames(i,1) = "") Then
        EmptyCounter = EmptyCounter + 1
    End If
Next i

End Sub
How to&Answers:

You can try this:

intN = Worksheets("Sheet1").Range("F2:F1000").Cells.SpecialCells(xlCellTypeConstants).Count
MsgBox intN

100% it works.

Answer:

There is no direct way to do it, as far as I understand. But you could run a simple loop to check if the values are equal to “” assuming string data.

For e.g.

For i = LBound(ArrayName) to UBound(ArrayName)
    If (ArrayName(i) = "") Then
        EmptyCounter = EmptyCounter + 1
    End If
Next i

If it’s numeric or other type of data, you may try variations of the above loop using functions such as IsEmpty(VariableName) etc.