Re: Defining multiple variables in VBA
This is a carry over from Rick's post #18 in this MrExcel thread (I didn't want to derail the thread):
Rick's post:
Quote:
Just so I can narrate, answer the first question with 5 and the second question with 9... the expected sum would be 14, not the 59 that is returned.
Code:
Sub Test()
Dim S1, S2, S3 As Long
S1 = InputBox("Enter first integer number:")
S2 = InputBox("Enter second integer number:")
S3 = S1 + S2
MsgBox S3
End Sub
I've been using the format: Dim x, y, z as type for years now and have recently been shown the errors of my ways. But I never thought it caused any actual problems in my code until Rick posted the above.
My question is this: I stepped thru the above code with watches on all the variables. It seems that Excel is assigning the non-explicitly declared variables as variants (expected) but then 'guessing' the type when they are assigned values. Do you have any idea what triggers the guess? I tried things like 5.0, 8.9 and the like to see if I can force the guess from String to Long or Double but the variables remained Variant/String types.
Just curious, really. I may have to go back through all of my VBA to see what has actually been happening behind my back while I wasn't looking %D.
Thanks,
CJ
https://www.youtube.com/watch?v=ySENWFIkL7c&lc=UgyqIYcMnsUQxO5CVyx4AaABAg
https://www.youtube.com/watch?v=yVgLmj0aojI&lc=UgwWg8x2WxLSxxGsUP14AaABAg. 9k3ShckGnhv9k89LsaigoO
https://www.youtube.com/watch?v=yVgLmj0aojI&lc=UgxxxIaK1pY8nNvx6JF4AaABAg. 9k-vfnj3ivI9k8B2r_uRa2
https://www.youtube.com/watch?v=yVgLmj0aojI&lc=UgxKFXBNd6Pwvcp4Bsd4AaABAg
https://www.youtube.com/watch?v=yVgLmj0aojI&lc=Ugw9X6QS09LuZdZpBHJ4AaABAg