View Single Post
  #24   Report Post  
Posted to microsoft.public.excel.programming
Tushar Mehta Tushar Mehta is offline
external usenet poster
 
Posts: 1,071
Default When do you need .Value?

When I want to point out to a regular poster, especially one who is
more often right than wrong, that their post demonstrates reckless
laziness, I go over their post with a fine-tooth comb; then repeat with
an even finer-tooth comb. Chances are the exercise will save me some
serious embarrassment -- like missing a first paragraph that read, in
part, "...Apparently, .Net does support some default properties..."

Notice the .Net part!

This sub-discussion, starting with Alan's query (Can you give an
illustration of what's meant by "VB.Net does not support a default
property") to my first response to the OP (...More importantly, AFAIK,
VB.Net does not support a default property...) morphed into one about
VB.Net's support of default properties.

--
Regards,

Tushar Mehta
www.tushar-mehta.com
Excel, PowerPoint, and VBA add-ins, tutorials
Custom MS Office productivity solutions

In article ,
says...
"Tushar Mehta" wrote...
...
But, Value definitely is not the default property for the range
object.

Dim x as object
x=cells(1,1) will create an object reference to the cell, whereas


No it won't. As written, when run it throws a Run-time error '91': Object
variable or With block variable not set. You need 'Set' at the beginning of
this statement.

x=cells(1,1).value will create a simple data type (of the appropriate
numeric/string type) that contains a value.

...

Not with x defined as an object it won't. Enter 1 in cell A1 and 2 in cell
A2, then modify your sample code slightly to be

Dim x As Object
Set x = Cells(1, 1)
x = Cells(2, 1).Value

The Set statement makes x an object reference to cell A1. The second
statement doesn't change x itself, rather it's interpretted as

x.Value = Cells(2, 1).Value

which you can test for yourself, since given the initial setup already
described, this statement sets the value of cell A1 to the value of cell A2,
namely, 2.

On the other hand, in the code

Dim x As Variant
x = Cells(1, 1)
x = Cells(2, 1).Value

the first statement sets x equal to the value of cell A1, and the second
call sets it to the value of cell A2. Modify it yet again to

Dim x As Variant
Set x = Cells(1, 1)
x = Cells(2, 1).Value

and the first statement sets x to an object reference to cell A1, but the
second statement sets x to the value in cell A2 rather than manipulating the
value in cell A1.

Moral: VERY dangerous (bordering on reckless) ever to try to use default
properties in left hand side terms of assignment statements. Default
properties are a laziness feature that leads to more time finding and fixing
the problems its use causes than time saved not having to type the default
property in the statement. This is especially the case in VB[A] when using
variant type variables.