Declare and use range in vba

I am completely new to VBA.
Today, as I developed the macro, I noticed something funny.

Using Rangehow it works:

Dim rg As Range     
Set rg = ActiveSheet.Range("A1:B2")  

Using Rangehow it does not work and leads to the error "Object variable not set":

Dim rg As Range   
rg = ActiveSheet.Range("A1:B2")  

but using Rangehow it works:

Dim rg,rg2 As Range  
rg = ActiveSheet.Range("A1:B2")  

How is this possible?

+4
source share
1 answer

You also find Variantreferences to objects.

A Range- object - a Variantcan be anything , including an object.

This is the correct way:

Dim rg As Range     
Set rg = ActiveSheet.Range("A1:B2")  

Because:

  • You explicitly declare rgas an object Range.
  • Set.

Set, VBA :

rg = ActiveSheet.Range("A1:B2") 

, rg Variant:

Dim rg,rg2 As Range  ' this is like doing Dim rg As Variant, rg2 As Range
rg = ActiveSheet.Range("A1:B2")  

VBA Variant ... .

+8

All Articles