I am quite new to VBA,
Today developing a macro I noticed something funny.
Using Range
like this is working :
Dim rg As Range
Set rg = ActiveSheet.Range("A1:B2")
Using Range
like this does not work and result in error "Object variable not set" :
Dim rg As Range
rg = ActiveSheet.Range("A1:B2")
but using Range
like this is working :
Dim rg,rg2 As Range
rg = ActiveSheet.Range("A1:B2")
How is it possible?
You are discovering Variant
and object references.
A Range
is an object - a Variant
can be anything including an object.
This is the correct way to go about it:
Dim rg As Range
Set rg = ActiveSheet.Range("A1:B2")
Because:
rg
as being a Range
object.Set
keyword.If you don't specity the Set
keyword, you're assigning an object reference using the VBA syntax for values assignments, and that's an error:
rg = ActiveSheet.Range("A1:B2")
If you declare multiple variables in the same instruction, and only specify a type for the last one, then rg
is a Variant
here:
Dim rg,rg2 As Range ' this is like doing Dim rg As Variant, rg2 As Range
rg = ActiveSheet.Range("A1:B2")
And VBA will happily let you assign a Variant
with just about anything... but things will blow up at run-time.
Expanding on Mathieu Guidon's answer:
If you want to specify two objects in the same instruction (one line), you should use the following syntax:
Dim rg as Range, rg2 As Range
This will correctly assign both rg
and rg2
as a range object.
Using Dim rg, rg2 As Range
, only rg2 is assigned as a range object (rg becomes a Variant), as Mathieu Guidon correctly explains.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With