r/visualbasic • u/NewEridu • 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 IfBut this presents two problems:
It's ugly and wildly inefficient
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
2
u/[deleted] May 05 '16
Solving your own problem? That's a paddlin!
https://www.youtube.com/watch?v=ZXQR-cPXlmY