What are the differences between Dim
and Set
? When to use each?
Context 1
Dim minhaString as String
minhaString = "Olá!"
Context 2
Set minhaString = "Olá!"
What are the differences between Dim
and Set
? When to use each?
Context 1
Dim minhaString as String
minhaString = "Olá!"
Context 2
Set minhaString = "Olá!"
Dim
and Set
are reserved words of some languages such as Visual Basic, VBScript, and Visual Basic for Applications .
The reserved word Dim
is used to declare a variable. The word Set
is used to assign a reference of an object to a variable.
Examples in VBScript:
Dim numero
numero = 2
Dim xlApp
Set xlApp = CreateObject("Excel.Application")
Note that when we are dealing with objects in VBScript and VBA it is necessary to use the word Set
before the variable. This happens because we are saving in the variable the reference of an object. On the other hand, when we are dealing with numbers, string, booleans this is not necessary. Because of this, the variable numero
above was given the 2
value without the need for the reserved word Set
.
So it is not the case to use Dim
or Set
as suggested in the question. They are words reserved for different uses. One to declare ( Dim
) another to assign ( Set
).
There is another use for the word Set that is in the definition of properties of a class, however, I believe that this fits the scope of the question, since the relation between Dim and Set was questioned.