Excel VBA: get value of cell, independent of cell's formatting

Go To StackoverFlow.com

10

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:

  • A1: 0.00001
  • A2: =A1
  • A3: =A1=A2

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:

  • B1: =f("A1")
  • B2: =f("A2")
  • B3: =B1=B2

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?

2012-04-04 23:39
by Joe
I'm using Excel 2010, and B3 is definitely coming up FALSE - Joe 2012-04-04 23:55
Guess it doesn't recalc if you only change the formatting.. - DJ. 2012-04-05 00:02


13

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
2012-04-04 23:58
by DJ.
Oh that's sneaky - uotonyh 2012-04-04 23:59
+1 good insigh - brettdj 2012-04-05 04:39


4

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.

2012-04-05 01:57
by brettdj
Nice link..... - DJ. 2012-04-05 04:38
Thanks for finding the explanatio - JMax 2012-04-05 07:18
Ads