Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is "Value" actually the default property of the Range object?

Tags:

vba

Before I begin I want to say that I realize you should never depend on default properties and I won't, but this is curious. I've always read that value is the default property for the Range Object, hence why this works:

Range("A1") = 2

However, this page claims that item is the default property of Range.

Additionally, this sub I made would suggest that cells is the default property instead:

Sub defaultprop()

Dim c As Variant


For Each c In Range("A1:A2")

    Debug.Print c.value

Next c

For Each c In Range("A1:A2").value

    Debug.Print c

Next c


End Sub
like image 528
apdm Avatar asked Oct 07 '15 15:10

apdm


1 Answers

The default member of the Range class is called _Default and is hidden. When you enable the "Show Hidden Members" feature in the Object Browser you can see it:

VBA Object Browser

It has the exact same signature as the .Item property, so one of them is arguably an alias for the other.(*)

In any case, Range also implements the collection interface. As such, it can be used in a For Each loop — and when you do that, the loop will call .Item with each iteration and assign the current item to the loop variable.

When used outside an enumeration, for example with Debug.Print, then .Value will be used, but I can't really explain why. Maybe someone else can come up with a hint.(*)


(*) As @GSerg points out in the comments, _Default() and _Item() are not exactly equal.

like image 161
Tomalak Avatar answered Oct 24 '22 04:10

Tomalak