View Single Post
  #25   Report Post  
Posted to microsoft.public.excel.programming
Harlan Grove Harlan Grove is offline
external usenet poster
 
Posts: 733
Default When do you need .Value?

I should have read the preceding branch of this thread first. It looks like
the code I commented on was supposed to be VB.NET rather than VBA. That
makes a difference.

Variants and explicit object variables holding object references have
different syntactic characteristics. An explicit object variable with no
property qualifier on either side of a [Let] assignment statement will cause
VBA to use the default property. This only works on the right hand side with
variants holding object references. This is syntactic, governed by how VBA
parses variants vs how it parses objects. A LHS variant can receive any
value VBA can generate on the RHS. A LHS object can't receive anything
itself in a Let assignment, so there's an implicit parsing step that uses
the object's default property.

On to .Value vs .Item. In XL2K, the following runs just fine.

Msgbox Range("A1:A2").Address

but oddly the following throws a runtime error

Msgbox Range.Item("A1:A2").Address

Seems awful odd for a default property not to work when used explicitly.
Gosh, do you suppose this could mean there are *ERRORS* in VBA online help?!
As if this wouldn't be the only one!!

There's also the syntactic problem that Item as default property is
unsatisfactory. Given

Dim x As Variant
x = Range("A1:A3").Item(1)

the Item property returns an *OBJECT* reference, to cell A1 in this case. In
the Let assignment statement, there's no way to assign this object to x. But
VBA is somehow able to assign something to x, and that something isn't an
object reference. What is it? The .Value property! If it weren't, then the
assignment statement above would lead to an infinite loop. The default
property of an object of type 'A' can't be another object of type 'A'.

It seems pretty clear to me that either the VBA parser has added logic for
handling Range objects or there are separate default properties for scalar
and object contexts, in which case .Value is the default property in scalar
context and .Cells is the default property in object context, and Cells is a
collection object, so its default property is .Item. That's the only way I
can see how

Range("A1:D3")(7)
Range("A1:D3")(2, 3)
Range("A1:D3").Cells(7)
Range("A1:D3").Cells(2, 3)
Range("A1:D3").Cells.Item(7)
Range("A1:D3").Cells.Item(2, 3)

all produce references to cell C2, but

Dim x As Variant
x = Range("A1:D3")(7)
x = Range("A1:D3")(2, 3)
x = Range("A1:D3").Cells(7)
x = Range("A1:D3").Cells(2, 3)
x = Range("A1:D3").Cells.Item(7)
x = Range("A1:D3").Cells.Item(2, 3)

all assign the value of cell C2 to x.