Declare and use range in vba
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:
- You're explicitly declaring
rg
as being aRange
object. - You're correctly assigning the object reference with the
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.