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
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
Option Explicit
As
their respective data type or object. This also gives the added benefit of intellisense
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With