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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With