Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it useless to use "Dim" to declare a variable if I don't write an "as something" after it?

Tags:

excel

vba

For example, are the following two codes the same? Is it unnecessary to use Dim if I don't write for example "as integer" after that?

Sub something()

MyNumber = 10

Worksheets(1).Range("A1") = MyNumber

End Sub

and

Sub something()

Dim MyNumber

MyNumber = 10

Worksheets(1).Range("A1") = MyNumber

End Sub
like image 863
Lanza Avatar asked Feb 16 '16 14:02

Lanza


1 Answers

If you Dimension a variable you are letting the compiler know that you are planning to use a certain amount of memory in advance of that variable being used. In most VBA programs on modern machines this wouldn't create a huge performance benefit, but is widely considered best practice.

One of the reasons that it is considered best practice is the auto-capitalization feature in the VBE which can help you as you're coding and debugging to spot any issues.

If you dimension a variable, and do the following:

Dim hWnd

hWnd = 1234
'// some more code....
hwnd = 2345

The VBE will automatically capitalize the w in the variable name and change it to hWnd - this can act as a small reassurance that you've got the right variable and not created a typo.


If you don't dimension a variable, you could easily find yourself in this kind of scenario:

hWnd = 1234
'// some code here
hwnd = 2345

In this scenario, the VBE will actually change the first occurrence of hWnd to hwnd. We then go on further to create a typo of hnwd and now our code looks like this:

hwnd = 1234
'// code here
hwnd = 2345
'// code here
hnwd = 3456

And suddenly you're scrolling through lines of code trying to find out why you're getting unexpected results.


TO BE SAFE

  1. Use Option Explicit
  2. Declare all variables As their respective data type or object. This also gives the added benefit of intellisense
like image 146
SierraOscar Avatar answered Sep 16 '22 11:09

SierraOscar