6

So there is a question on what DIM is, but I can't find why I want to use it.

As far as I can tell, I see no difference between these three sets of code:

'Example 1
myVal = 2

'Example 2
DIM myVal as Integer
myVal = 2

'Example 3
DIM myVal = 2

If I omit DIM the code still runs, and after 2 or 3 nested loops I see no difference in the output when they are omitted. Having come from Python, I like to keep my code clean*.

So why should I need to declare variables with DIM? Apart from stylistic concerns, is there a technical reason to use DIM?

* also I'm lazy and out of the habit of declaring variables.

Community
  • 1
  • 1
  • And for reference, [What does the keyword set do in VBA?](http://stackoverflow.com/questions/349613/what-does-the-keyword-set-actually-do-in-vba) –  Jun 24 '14 at 04:43
  • Dim allocates memory. By specifing type you specify how much memory (else it is a variant which is whatever datatype vb decides plus 8 bytes). VB will allocate on first use anyway. Dim is effecient code versus not using dim which in slower and uses more memory. VB has an old feature where you can specify type as in `"A$="a string"` (`% Integer & Long ! Single # Double $ String @ Currency `. As others mentioned it does double duty of preventing spelling mistakes. – phd443322 Jun 24 '14 at 05:10
  • Agree with @phd443322. Also when you are trying to work with specific data types (e.g. arguments on your function and subs, returned value from a function, etc.) you can traps errors when the output is not of the data type you expect. That gives you visibility of what your code actually does and aids you as well in trouble-shooting. – L42 Jun 24 '14 at 05:13
  • Since there is no way to `free` memory, I find it odd to call it allocating memory. Also, we are talking about a single variable in a behemoth of a program like Excel, is one dynamically allocated variable going to bring it down? –  Jun 24 '14 at 05:15
  • @L42 So the big advantage I can see is enforced data typing then? –  Jun 24 '14 at 05:15
  • I guess it depends on your case. If it is as simple as what you describe, it might not matter at all. But if you're working on larger scale wherein there are a lot of functions and subs involved, it would be beneficial to have a control of how your data is processed. Explicitly defining the data type is an added control for me. This is my opinion really, but helped me reducing unexpected results. – L42 Jun 24 '14 at 05:23
  • 2
    All local variables are stored on the stack as with all languages (and most parameters to functions). When a sub exits the stack is returned to how it was before the sub executed. So all memory is freed. Strings and objects are stored elsewhere in a object manager or string manager and the stack contains a pointer but vb looks after freeing it. Seting a vbstring (a bstr) to zero length frees all but two bytes. That's why we try to avoid global variables. – phd443322 Jun 24 '14 at 05:33
  • 2
    In scripting type programs, typeless programming has many advantages. Programs are short and use few variables so memory and speed don't matter - it will be fast enough. As programs get more complex it does matter. VB was designed for typeless programming as well as typed programming. For most excel macros, typeless programming is fine and is more readable. Vbscript only supports typeless programming (and you can paste it into vba/vb6). – phd443322 Jun 24 '14 at 06:00
  • 2
    FWIW, Example 3 will not work in VBA. You cannot declare and assign a variable on the same line. – Rory Jun 24 '14 at 09:04
  • @LegoStormtroopr On the surface, what your VBA lines do above looks like what python does, but a lot more is going on under the hood. The first one assigns a variant. [`Variant` is a COM wrapper object](http://bytecomb.com/vba-internals-variant-variables-and-pointers-in-depth/) that on construction, assignment etc makes Windows API calls, hence the memory and performance overhead. Check also the `Variant` section of [this](http://bytecomb.com/vba-internals-whats-in-a-variable/) link. – Ioannis Jun 24 '14 at 09:13
  • @Rory correct unless the variable is a constant or passed as an optional parameter –  Jun 24 '14 at 15:26
  • 2
    @mehow a constant is, by definition, not a variable. ;) I take your point about optional arguments. – Rory Jun 24 '14 at 15:31
  • @Rory I am not sure how to interpret that constant is not a variable but I will look that up :) –  Jun 24 '14 at 15:33
  • @mehow It doesn't *vary*, it's constant. :) – Rory Jun 24 '14 at 15:36
  • @Rory that's exactly what I thought you would say :) I would define the word `variable` as a storage (either value or reference) not taking into consideration whether it can change. –  Jun 24 '14 at 15:39
  • 2
    @mehow That's up to you. The VBA language specification would not agree. ;) – Rory Jun 24 '14 at 15:55
  • @Rory I've gotta find it:) not to argue with you just for myself so i can go to sleep in peace ;P –  Jun 24 '14 at 15:57
  • @mehow it's here: http://msdn.microsoft.com/en-us/library/dd361851.aspx – Rory Jun 24 '14 at 16:04

3 Answers3

12

Using Dim makes the intentions of your code explicit and prevents common mistakes like a typo actually declaring a new variable. If you use Option Explicit On with your code (which I thoroughly recommend) Dim becomes mandatory.

Here's an example of failing to use Dim causing a (potentially bad) problem:

myVar = 100

' later on...

myVal = 10      'accidentally declare new variable instead of assign to myVar

Debug.Print myVar     'prints 100 when you were expecting 10

Whereas this code will save you from that mistake:

Option Explicit

Dim myVar as Integer
myVar = 100

' later on...

myVal = 10    ' error: Option Explicit means you *must* use Dim

More about Dim and Option Explicit here: http://msdn.microsoft.com/en-us/library/y9341s4f.aspx

Matt Coubrough
  • 3,739
  • 2
  • 26
  • 40
  • Sorry, I'm after a technical reason and I've clarified the answer as such. While interesting points, they don't justify the additional commands required, and also doesn't address my "Example 2" with declaring with a type instead of a value. –  Jun 24 '14 at 04:59
  • 13
    Since you never make mistakes and don't care about performance, you should never declare your variables. The rest of us benefit from the compiler's help. – Mike Woolf Jun 24 '14 at 05:02
  • @MikeWoolf Make an answer telling me how DIM improves performance - because so far I see claims of allocation of memory (without the explicit ability to free again) that would have been necessary in VB3, but now just seem outdated. –  Jun 24 '14 at 05:17
  • The problem is that you've been given some very good technical reasons to declare your variables, yet reject these on grounds that are unclear in the extreme. A variant is much larger than an int and must undergo runtime checks on every operation. – Mike Woolf Jun 24 '14 at 05:37
  • @MikeWoolf The only place a "variant" is described is briefly without explanation in a comment. This question isn't a "very good technical reason" its a stylistic reason, and a type safety reason. But both of those can be over come with good discipline. The best *technical answer* with an actual explanation is a comment from phd443322 regarding scoping and memory freeing. –  Jun 24 '14 at 06:09
11

Any variable used without declaration is of type Variant. While variants can be useful in some circumstances, they should be avoided when not required, because they:

  1. Are slower
  2. Use more memory
  3. Are more error prone, either through miss spelling or through assigning a value of the wrong data type
chris neilsen
  • 52,446
  • 10
  • 84
  • 123
  • 2
    ++ chris. Also worth mentioning that some `Variant` type is worked out by the compiler at runtime and it may not always be what you think it was going to be. [***Very good follow up***](http://stackoverflow.com/questions/21386768/why-am-i-having-issues-assigning-a-range-to-an-array-of-variants) –  Jun 24 '14 at 15:30
5

Moderators, I'm making an effort, assuming you'll treat me with due respect in thefuture.

All local variables are stored on the stack as with all languages (and most parameters to functions). When a sub exits the stack is returned to how it was before the sub executed. So all memory is freed. Strings and objects are stored elsewhere in a object manager or string manager and the stack contains a pointer but vb looks after freeing it. Seting a vbstring (a bstr) to zero length frees all but two bytes. That's why we try to avoid global variables.

In scripting type programs, typeless programming has many advantages. Programs are short and use few variables so memory and speed don't matter - it will be fast enough. As programs get more complex it does matter. VB was designed for typeless programming as well as typed programming. For most excel macros, typeless programming is fine and is more readable. Vbscript only supports typeless programming (and you can paste it into vba/vb6).

phd443322
  • 493
  • 3
  • 4
  • 3
    `dynamic typing` vs `static typing` is the exact terminology. Typeless would imply that variables have no type, which is not true. – z̫͋ Jun 24 '14 at 11:10