MrExcel Publishing
Your One Stop for Excel Tips & Solutions

Question about Dim statement


Posted by Josh on December 26, 2001 4:49 PM

Hi

I have a general question on Dim statements

Let say I have Dim X as integer

and in my code I have

for x = 1 to something

My question is, is there any reason to say dim x as integer since it always will be an integer. I could put just Dim x. Is there a difference as far as the code is concerned or is the as ("whatever") there just to make the code easier to understand for other humans?

Thanks


Posted by Russell Hauf on December 26, 2001 5:30 PM

The difference is just in how much memory is allocated to the variable. It's negligible in small programs, but it's good programming practice to use the variable type you will be using. If you just use

Dim X

then X will be of type Variant, which takes more memory than an integer, but will accept values of type integer. Oh, Variants are also slower than explicitly defined types due to the fact that they need to keep track of what type of data they are holding.

Another reason not to just use Variants is that they can be passed any type of value - so if you accidentally pass a string to your variable that you are supposedly using for Integers, it will accept that without giving an error...so if you try to multiply it later (or something like that), you will get an error.

Hope this helps,

Russell

Posted by Josh on December 26, 2001 6:18 PM

Thanks for the info (NT)