Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare and use range in vba

Tags:

range

excel

vba

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?

like image 768
SJGD Avatar asked Dec 10 '14 14:12

SJGD


2 Answers

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:

  1. You're explicitly declaring rg as being a Range object.
  2. 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.

like image 131
Mathieu Guindon Avatar answered Oct 13 '22 23:10

Mathieu Guindon


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.

like image 21
Albin Avatar answered Oct 13 '22 23:10

Albin