vba 在vba中声明和使用范围
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27403834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Declare and use range in vba
提问by SJGD
I am quite new to VBA,
Today developing a macro I noticed something funny.
我对 VBA 很陌生,
今天开发一个宏,我注意到一些有趣的事情。
Using Range
like this is working :
Range
像这样使用是有效的:
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" :
Range
像这样使用不起作用并导致错误“未设置对象变量”:
Dim rg As Range
rg = ActiveSheet.Range("A1:B2")
but using Range
like this is working :
但Range
像这样使用是有效的:
Dim rg,rg2 As Range
rg = ActiveSheet.Range("A1:B2")
How is it possible?
这怎么可能?
回答by Mathieu Guindon
You are discovering Variant
and object references.
您正在发现Variant
对象引用。
A Range
is an object- a Variant
can be anythingincludingan object.
ARange
是一个对象- aVariant
可以是任何东西,包括一个对象。
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.
- 您明确声明
rg
为Range
对象。 - 您正确地使用
Set
关键字分配了对象引用。
If you don't specity the Set
keyword, you're assigning an object reference using the VBA syntax for valuesassignments, and that's an error:
如果您没有指定Set
关键字,则您正在使用 VBA 语法为值分配分配对象引用,这是一个错误:
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:
如果在同一条指令中声明多个变量,并且只为最后一个指定类型,那么这里rg
是一个Variant
:
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.
VBA 会很高兴地让你分配一个Variant
几乎任何东西......但事情会在运行时爆炸。
回答by Albin
Expanding on Mathieu Guidon's answer:
扩展 Mathieu Guidon 的回答:
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.
这将正确分配rg
和rg2
作为范围对象。
Using Dim rg, rg2 As Range
, only rg2 is assigned as a rage object (rg becomes a Variant), as Mathieu Guidon correctly explains.
使用 时Dim rg, rg2 As Range
,只有 rg2 被指定为 rage 对象(rg 成为变体),正如 Mathieu Guidon 正确解释的那样。