What does the keyword Set actually do in VBA?

2018-12-31 08:30发布

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.

7条回答
临风纵饮
2楼-- · 2018-12-31 08:36

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.

查看更多
后来的你喜欢了谁
3楼-- · 2018-12-31 08:38

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

Set assigns an object reference. For all other assignments the (implicit, optional, and little-used) Let statement is correct:

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

Let i = 0
Let i = FunctionReturningAValue(SomeArgument)

' or, more commonly '

i = 0
i = FunctionReturningAValue(SomeArgument)
查看更多
栀子花@的思念
4楼-- · 2018-12-31 08:42

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

 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)
查看更多
梦醉为红颜
5楼-- · 2018-12-31 08:45

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

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

Dim WS As Worksheet

Set WS = ActiveWorkbook.Worksheets("Sheet1")

WS.Name = "Amit"

查看更多
宁负流年不负卿
6楼-- · 2018-12-31 08:47

From 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.

查看更多
只靠听说
7楼-- · 2018-12-31 08:49

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".

查看更多
登录 后发表回答