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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 05:29:05  来源:igfitidea点击:

Declare and use range in vba

excelvbarange

提问by SJGD

I am quite new to VBA,
Today developing a macro I noticed something funny.

我对 VBA 很陌生,
今天开发一个宏,我注意到一些有趣的事情。

Using Rangelike this is working :

Range像这样使用是有效的:

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

Using Rangelike this does not work and result in error "Object variable not set" :

Range像这样使用不起作用并导致错误“未设置对象变量”:

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

but using Rangelike this is working :

Range像这样使用是有效的:

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

How is it possible?

这怎么可能?

回答by Mathieu Guindon

You are discovering Variantand object references.

您正在发现Variant对象引用。

A Rangeis an object- a Variantcan 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:

因为:

  1. You're explicitly declaring rgas being a Rangeobject.
  2. You're correctly assigning the object reference with the Setkeyword.
  1. 您明确声明rgRange对象。
  2. 您正确地使用Set关键字分配了对象引用。


If you don't specity the Setkeyword, 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 rgis a Varianthere:

如果在同一条指令中声明多个变量,并且只为最后一个指定类型,那么这里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 Variantwith 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 rgand rg2as a range object.

这将正确分配rgrg2作为范围对象。

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 正确解释的那样。