关键字 Set 在 VBA 中实际上有什么作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/349613/
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-08 09:31:21  来源:igfitidea点击:

What does the keyword Set actually do in VBA?

vbavariable-assignment

提问by Jon Artus

Hopefully an easy question, but I'd quite like a technical answer to this!

希望是一个简单的问题,但我非常想要一个技术性的答案!

What's the difference between:

有什么区别:

i = 4

and

Set i = 4

in VBA? I know that the latter will throw an error, but I don't fully understand why.

在 VBA 中?我知道后者会抛出错误,但我不完全明白为什么。

采纳答案by Treb

setis used to assign a reference to an object. The C equivalent would be

set用于为对象分配引用。C 等价物将是

 int i;
int* ref_i;

i = 4; // Assigning a value (in VBA: i = 4)
ref_i = &i; //assigning a reference (in VBA: set ref_i = i)

回答by Tomalak

In your case, it will produce an error. :-)

在您的情况下,它会产生错误。:-)

Setassigns an object reference. For all other assignments the (implicit, optional, and little-used) Letstatement is correct:

Set分配一个对象引用。对于所有其他赋值,(隐式、可选和很少使用)Let语句是正确的:

Set object = New SomeObject
Set object = FunctionReturningAnObjectRef(SomeArgument)

Let i = 0
Let i = FunctionReturningAValue(SomeArgument)

' or, more commonly '

i = 0
i = FunctionReturningAValue(SomeArgument)

回答by Galwegian

From MSDN:

MSDN

Set Keyword:In VBA, the Set keyword is necessary to distinguish between assignment of an object and assignment of the default property of the object. Since default properties are not supported in Visual Basic .NET, the Set keyword is not needed and is no longer supported.

Set关键字:在VBA中,Set关键字是区分对象赋值和对象默认属性赋值所必需的。由于 Visual Basic .NET 不支持默认属性,因此不需要并且不再支持 Set 关键字。

回答by LeppyR64

Set is used for setting object references, as opposed to assigning a value.

Set 用于设置对象引用,而不是分配值。

回答by Sean

Off the top of my head, Set is used to assign COM objects to variables. By doing a Set I suspect that under the hood it's doing an AddRef() call on the object to manage it's lifetime.

在我的脑海中,Set 用于将 COM 对象分配给变量。通过执行 Set 我怀疑在幕后它正在对对象执行 AddRef() 调用来管理它的生命周期。

回答by Eric Wang

So when you want to set a value, you don't need "Set"; otherwise, if you are referring to an object, e.g. worksheet/range etc., you need using "Set".

所以当你想设置一个值时,你不需要“Set”;否则,如果您指的是一个对象,例如工作表/范围等,则需要使用“设置”。

回答by Amit Singh

Set is an Keyword and it is used to assign a reference to an Object in VBA.

Set 是一个关键字,用于在 VBA 中为对象分配引用。

For E.g., *Below example shows how to use of Set in VBA.

例如,*下面的示例显示了如何在 VBA 中使用 Set。

Dim WS As Worksheet

Dim WS 作为工作表

Set WS = ActiveWorkbook.Worksheets("Sheet1")

设置 WS = ActiveWorkbook.Worksheets("Sheet1")

WS.Name = "Amit"

WS.Name = "阿米特"