Declare and use range in vba

强颜欢笑 提交于 2019-12-10 13:37:46

问题


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?


回答1:


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.




回答2:


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 rage object (rg becomes a Variant), as Mathieu Guidon correctly explains.



来源:https://stackoverflow.com/questions/27403834/declare-and-use-range-in-vba

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!