VBA: Declare Variables Online

1

To declare variables in VBA , I always used the following method: all variables of the same type I would put on a same line and declare their type only at the end, as in the example below:

Dim RngSource, RngDestin, RngCalc As Range
Dim i, j As Long
Dim n As Integer
Dim Tot1, Tot2, Cust As String

Recently, searching the internet, I noticed that some sources say that this way of declaring variables is wrong, since only the last variable is sized by the declared type. For example, in the Dim i, j As Long line, only the variable j will be scaled as Long , whereas the i variable would be being scaled as the generic variable Variant . Supposedly, the correct form of statement would be:

Dim RngSource As Range, RngDestin As Range, RngCalc As Range
Dim i As Long, j As Long
Dim n As Integer
Dim Tot1 As String, Tot2 As String, Cust As String

However, I still find sources on the internet recommending the previous model to shorten the size of the code.

After all: what is the correct way?

    
asked by anonymous 11.04.2017 / 16:28

1 answer

2

You need to define the type of each variable, otherwise its type will only be defined after assigning a value, just like in javascript.

With the function VarType you can check this:

Dim i, j As Long

Debug.Print VarType(i) 'Resultado: 0
Debug.Print VarType(j) 'Resultado: 3

i = "texto"
Debug.Print VarType(i) 'Resultado: 8

Based on the table provided by Microsoft itself:

link

    
11.04.2017 / 18:27