Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
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? –  asantaballa Jul 26 '13 at 9:49
 
I see so 0 is the "empty element" –  karamell Jul 26 '13 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 –  rags Jul 26 '13 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". –  asantaballa Jul 26 '13 at 9:57
add comment

1 Answer

up vote 1 down vote accepted
    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
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.