In Excel VBA, Range("A1").Value
should return the underlying value of the range A1 on the worksheet. But I'm getting a different value if the cell is formatted as Accounting.
How do I get the actual underlying value of the cell?
Worksheet
Make a new document, enter the following values in cells:
As you'd expect, A3 results in TRUE
. Now change the formatting of A2 to Accounting, using 2 decimal places. A2 now reads $ 0.00
, but the underlying value is still 0.00001
, so A3 is still TRUE
.
VBA
Make a new module and add in the following function:
Function f(addr As String)
f = Range(addr).Value
End Function
As you can see, this just gets the value of a range using the Value
method of the Range
object.
Worksheet
Back to the worksheet. Enter the following values:
A1
and A2
have the same underlying value, but B1
and B2
don't, even though they're both calculated using the Value
method of A1
and A2
.
The expression in A3
(=A1=A2
) is accessing the actual underlying value of A1
and A2
. How do I access these values in VBA?
It initally came up TRUE for me as well because I added the formatting after I entered the formulas.
To repro - re-edit B2.
To get the underlying value you need to use the VALUE2 property which seems to ignore the formatting:
Function f(addr As String)
f = Range(addr).Value2
End Function
The issue with using VBA and Value with currency formatted cells beyond 4 decimals points is covered well by this post at Dick's blog
If you type a number into an unformatted cell in Excel, that number is stored in the Double data type. When you format that number, you show it in a specific way, but you don’t change the number. For instance, if you format the number 1 as a Comma style, you get 1.00. The underlying data is still a 1, you’re just showing it differently. The Date format and the Currency format are two exceptions to this rule.
When you format something as a Date or Currency, you actually change the underlying data type (of the value stored in the Value property). When it comes to the Date format, this is semantics because you can switch between the Date and Double data types without any change to the data. Not so much with the Currency data type. Currency only supports four decimal places, so jamming a Double with, say, five decimals into a Currency data type will result in a different number.
B3
is definitely coming upFALSE
- Joe 2012-04-04 23:55