What does the keyword Set actually do in VBA?

前端 未结 7 2416
既然无缘
既然无缘 2020-11-22 04:26

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

What\'s the difference between:

i = 4

and



        
相关标签:
7条回答
  • 2020-11-22 04: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.

    0 讨论(0)
  • 2020-11-22 04:47

    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.

    0 讨论(0)
  • 2020-11-22 04:49

    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)
    
    0 讨论(0)
  • 2020-11-22 04:52

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

    0 讨论(0)
  • 2020-11-22 04:56

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

    0 讨论(0)
  • 2020-11-22 04:57

    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"

    0 讨论(0)
提交回复
热议问题