问题
As a follow-up question to an answer I posted here I would like to know why the following doesn't error, is this a possible bug in VBA?
Take the following data:

If we use the following VBA code, we will receive an error because we need to use the numeric value of the date to match:
'//Produces error
Debug.Print WorksheetFunction.Match(Range("C3").Value, Range("A1:A14"), 0)
and so either of these statements will work:
'// Cast to Long
Debug.Print WorksheetFunction.Match(CLng(Range("C3").Value), Range("A1:A14"), 0)
'// Access .Value2 property directly
Debug.Print WorksheetFunction.Match(Range("C3").Value2, Range("A1:A14"), 0)
However as pointed out by Jean-François Corbett, if we don't specify a property it also works:
Debug.Print WorksheetFunction.Match(Range("C3"), Range("A1:A14"), 0)
So if .Value
doesn't work, and this is the default property of the Range
object - why does it work in the above example?
Could this be a bug? Or is there some level of evaluation taking place that counteracts this?
回答1:
I don't think it is a bug. If you run below macro:
Debug.Print Range("C3"), Range("C3").Value, Range("C3").Value2
1st two will return returns identical results.
3/2/2015 3/2/2015 42065
Which confirms the default property as Value
for Range Object
.
It is worth noting though that if you explicitly use Value
all throughout, it will work as well.
Debug.Print WorksheetFunction.Match(Range("C3").Value, Range("A1:A14").Value, 0)
So I think that it is another manifestation of the issue once described here.
If you don't explicitly define Value
property for both, Excel is smart enough to assume that you're matching Values
. However, if you explicitly imply one property but leave Excel guessing for the other, it will not work.
来源:https://stackoverflow.com/questions/29533627/default-range-property-produces-unexpected-results