Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA variable/array default values

Consider the declarations

Dim x As Double
Dim avg(1 To 10) As Double

What are the default values in x and avg?

Through testing, I want to say that x is initialized to zero. Likewise, I want to say that all elements in avg were initialized to zero.

However, can I write code that depends on this? Or are the default initialization values actually indeterminate?

like image 381
Prashant Kumar Avatar asked Oct 02 '11 14:10

Prashant Kumar


3 Answers

If you specify a data type but do not specify an initializer, Visual Basic initializes the variable to the default value for its data type, which for all numeric types is 0 (zero).

When you run a macro, all the variables are initialized to a value. A numeric variable is initialized to zero, a variable length string is initialized to a zero-length string (""), and a fixed length string is filled with the ASCII code 0. Variant variables are initialized to Empty. An Empty variable is represented by a zero in a numeric context and a zero-length string ("") in a string context.

Ref.

like image 77
Mitch Wheat Avatar answered Sep 26 '22 01:09

Mitch Wheat


You can write code that implicitly depends on a given data type's default value, but that doesn't mean you always should, because it isn't quite as obvious what you're doing, which may confuse the next person reading your code (and that person could be you a year from now).

You can't go wrong with explicitly assigning an initial value to your variables. If you want, you can do that on the same line as the declaration:

Dim x As Double: x = 0

Of course, it's a little more involved for arrays, but usually there's a convenient place to initialize them further down in your code, where you're traversing them anyway.

like image 40
Jean-François Corbett Avatar answered Sep 26 '22 01:09

Jean-François Corbett


Yes, you should be able to depend on number types being initialize to 0 in VBA since that's their default value.

However, if it makes you worry, and the starting values are so important, then my reccomendation is that you just explicitly assign the value 0 to them (although you really don't need to).

like image 2
aevanko Avatar answered Sep 24 '22 01:09

aevanko