Pardon me as am a newbie in VBA.
Sometimes I use
Dim r as Range
r = Range("A1")
Other times I use
Set r = Range("A1")
What is the difference? And when should I use what?
Pardon me as am a newbie in VBA.
Sometimes I use
Dim r as Range
r = Range("A1")
Other times I use
Set r = Range("A1")
What is the difference? And when should I use what?
Dim
is short for Dimension and is used in VBA and VB6 to declare local variables.Set on the other hand, has nothing to do with variable declarations. The
Set
keyword is used to assign an object variable to a new object.Hope that clarifies the difference for you.
According to VBA help on SET statement it sets a reference to an object.so if you change a property the actual object will also changes.
the other Vars properties also changes,so:
actualy all vars are the same!
If a variable is defined as an object e.g. Dim myfldr As Folder, it is assigned a value by using the keyword, "Set".
There's no reason to use
set
unless referring to an object reference. It's good practice to only use it in that context. For all other simple data types, just use an assignment operator. It's a good idea todim
(dimension) ALL variables however:Examples of simple data types would be
integer
,long
,boolean
,string
. These are just data types and do not have their own methods and properties.An example of an
object
would be aRange
, aWorksheet
, or aWorkbook
. These have their own methods and properties.If you try to use the last line without
Set
, VB will throw an error. Now that you have anobject
declared you can access its properties and methods.Dim
simply declares the value and the type.Set
assigns a value to the variable.Dim
declares the variable.Set
sets the variable to an object reference.However, I don't think this is what you're really asking.
This will never work. Without
Set
you will receive runtime error #91 Object variable or With block variable not set. This is because you must useSet
to assign a variables value to an object reference. Then the code above will work.I think the code below illustrates what you're really asking about. Let's suppose we don't declare a type and let
r
be aVariant
type instead.So, let's break down what happens here.
r
is declared as a Variantr
is set to theRange
containing cell "A1"r
is set to the value of the default property ofRange("A1")
.In this case, the default property of a Range is
.Value
, so the following two lines of code are equivalent.For more about default object properties, please see Chip Pearson's "Default Member of a Class".
As for your
Set
example:This wouldn't work without first declaring that
r
is aRange
orVariant
object... using theDim
statement - unless you don't haveOption Explicit
enabled, which you should. Always. Otherwise, you're using identifiers that you haven't declared and they are all implicitly declared as Variants.