PDA

View Full Version : Declaring a variable and assigning a value to it at once



chamster
09-14-2007, 06:03 AM
I'm using Option Explicit, hence needing to use Dim thas As That. My code looks typically as this.
Dim intNum as Integer
intNum=0

I wonder if there's a VALID way to declare AND assign at the same time. Something along the ways of C looking like this.

private int
num1 = 3,
num2 = 4;

Is it doable in VBA? Should it be done that way? Why? Why not?

rory
09-14-2007, 06:09 AM
No, it's not. You can declare constants that way, but not variables.
Incidentally, Option Explicit does not require you to declare a variable as a particular type, it just requires you to declare all variables that you use.

Norie
09-14-2007, 07:38 AM
chamster

As well as what Rory has said you should also know that in your example there is no need to set the variable to 0 - it already is.:)

chamster
09-14-2007, 09:09 AM
Is it always the case that a variable just declared to Integer is initialized to zero? I'm guessing the same goes for Double, Long and other numerical values. For String it will be "" and for Bool it will be False, i'd guess.

But what will it be for, say, a Range or Worksheet?

Norie
09-14-2007, 09:14 AM
chamster

I can't say for sure but I think that's right for numerical data types.

I think you are also right about String and Boolean.

As to ranges/worksheets/other objects I think they would just be Nothing/Empty.

To check that I would suggest you declare some variables and then add watches to them, then step through the code with F8 and see what there values are before you assign anything to them.

Bob Phillips
09-14-2007, 09:18 AM
As well as what Rory has said you should also know that in your example there is no need to set the variable to 0 - it already is.:)

It is a trusting man that will trust that to be true in all future releases of an MS product.

unmarkedhelicopter
09-14-2007, 11:09 AM
I'm sure I've seen statements in MS VBA texts that numeric variables are initialised as 0, boolean false and string "".
For the others it's a bit like guessing the meaning of life, the universe and everything (in which case it's 42)