3

Noob question: I want to count the non empty elements of an array?

My attempt:

Dim Arr(1 To 15) As Double
'populating some of the elements of Arr
'...

Dim nonEmptyElements As Integer, i As Integer
nonEmptyElements = 0: i = 0
For i = LBound(Arr) To UBound(Arr)
    If Not Arr(i) = "" Then
        nonEmptyElements = nonEmptyElements + 1
    End If
Next

With this program I get the error: Type mismatch on If statement.

If try to change the if condition to If Not IsEmpty(Arr(i)) Then and i get nonEmptyElements = 15 as a result.

Any suggestions on how to complete the code?

4
  • 4
    You're defining Arr as Double so can't contain "empty" elements like it could if it was variant. They're always a number. So I think the program is working right, just not doing what you're looking for. Say more about what your goal is? Commented Jul 26, 2013 at 9:49
  • I see so 0 is the "empty element" Commented Jul 26, 2013 at 9:51
  • 1
    Can the array contain 0 as an element ? If not, write the if statement as below: If Arr(i) <> 0 Then Commented Jul 26, 2013 at 9:53
  • 2
    If you wanted to treat it that way. May depend on your application. may be ok for, say, lottery system, where lottery number is never zero. For accounting system where a budget amount could be zero you would need to use variant type to allow "true blanks". Commented Jul 26, 2013 at 9:57

2 Answers 2

2
    Dim Arr(0 To 15) As Double
    Arr(6) = 1.2
    Arr(3) = 7
    Dim nonEmptyElements As Integer, i As Integer
    nonEmptyElements = 0 : i = 0
    For i = LBound(Arr) To UBound(Arr)
        If Not Arr(i) = 0 Then
            nonEmptyElements = nonEmptyElements + 1
        End If
    Next

A double value by default is 0.0, so check if:

Arr(i) = 0
Sign up to request clarification or add additional context in comments.

Comments

1
Application.CountA(myarray)

CountA is a worksheet function for counting non-empty values.

Applies only to VBA6, does not work in VBA7.

1 Comment

@ExcelDevelopers you're right, but note that it worked in VBA6. CountA behavior is different in VBA6 and VBA7.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.