VBA: Declare variables online

Asked

Viewed 1,070 times

1

To declare variables in VBA, I always used the following method: all variables of the same type I put in the same line and declared 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 found that some sources say that this way of declaring variables is mistaken, because only the last variable is dimensioned by the declared type. For example: on the line Dim i, j As Long, only the variable j will be sized as Long, already the variable i would be 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 that recommend the previous model to shorten the code size.

After all: which is the correct form?

  • 1

    For VB.NET I can assure you that this statement is a fallacy, IE, all variables of the line receive the type defined last. But I can’t guarantee for VB Classic (which is your case), I even looked for how to run some code on VB6 or some compiler online, but I didn’t really find anything that would help.

  • Young, VBA does not apply only to excel. Please keep the question without this tag.

1 answer

2


You need to define the type of each variable, otherwise the type of the same will only be defined after the assignment of a value, just as it occurs in javascript.

With the function VarType it is possible to verify 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:

VarType

https://msdn.microsoft.com/en-us/library/aa263402(v=vs.60). aspx

Browser other questions tagged

You are not signed in. Login or sign up in order to post.