Why should I use a DIM statement in VBA or Excel?

So, there is a question about what DIMis , but I can not find why I want to use it.

As far as I can tell, I don't see the 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 works, and after 2 or 3 nested loops, I see no difference in output when they are omitted. Coming from Python, I like to repair my code *.

So why do I need to declare variables with DIM? Besides stylistic issues, is there a technical reason to use DIM?

* I am also lazy and not used to declaring variables.

+4
source share
3

, , Variant. , , , :

  • ,
+10

Dim , , . Option Explicit On ( ) Dim .

Dim, ( ) :

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

:

Option Explicit

Dim myVar as Integer
myVar = 100

' later on...

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

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

+10

, , , .

, ( ). sub , , , . , . , , vb . vbstring (bstr) , . .

. , - ​​ . . VB , . excel . Vbscript ( vba/vb6).

+5

Source: https://habr.com/ru/post/1545784/


All Articles