r/visualbasic • • May 05 '16

[VBS] Adding only numeric variables

I have something like this:

var1 = 34.5
var2 = 61.5
var3 = 5.9
.... 'etc
 newVar = var1 + var2 + var3 + ....

But var1 through varX could have a non-numeric value, and I want to sum them if they are valid numbers. My first thought is:

If isNumeric(var1) And isNumeric(var2) Then
    newVar = var1 + var2
End If

If isNumeric(var3) and isNumeric(var4) Then
    newVar = newVar + var4 + var4
End If

But this presents two problems:

  1. It's ugly and wildly inefficient

  2. If var1 is numeric and var2 is NOT, then var1 gets left out of the sum

Is there a way to do this in a compact loop? Can someone point me in the right direction?


EDIT! I solved it with this:

arrVals(0) = var1
arrVals(1) = var2
arrVals(2) = var3
.... 'etc

For i = 0 to UBound(arrVals)
    If IsNumeric(arrVals(i)) Then
        newVar = newVar + arrVals(i)
    End If
Next
5 Upvotes

1 comment sorted by

View all comments

2

u/[deleted] May 05 '16

Solving your own problem? That's a paddlin!

https://www.youtube.com/watch?v=ZXQR-cPXlmY