When one should use Set [e.g for SpecialCells return value]?

后端 未结 4 1279
逝去的感伤
逝去的感伤 2020-11-27 23:39

I am afraid I misunderstand the documentation of VBA for excel, I have this line which seems to be an error:

Range a = Selection.SpecialCells(xlCellTypeConst         


        
4条回答
  •  离开以前
    2020-11-28 00:12

    Range a = Selection.SpecialCells(xlCellTypeConstants, 23)
    

    This is not valid VBA, regardless of data type. You don't declare variable type in front of variable name, as you would do in C#, and you don't initialize variable at the point of declaration, as you would do in VB.NET.

    You can do:

    Dim a As Range
    Set a = Selection.SpecialCells(xlCellTypeConstants, 23)
    

    This will save a reference to the range into a.

    You can also do:

    Dim a As Variant
    a = Selection.SpecialCells(xlCellTypeConstants, 23)
    

    This will save in a a 2D array of values of cells in the range.

    Returns a Range object that represents all the cells that match the specified type and value.

    But it actually returns a byRef object and that is why I have to use Set.

    There are no byval objects in VBA. All objects are byref, and when you want to copy a reference to an object, you always use Set. The reason why you need Set is default properties. Each object can have a default property that is requested when only object name is provided. This creates ambiguity, so you need to say Set when you need to manipulate the object reference itselt, and omit Set when you want the default property of an object. The default property of Range is Value.

提交回复
热议问题