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

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.

Leave a Comment