Home » excel » Excel VBA unexpected truncation

Excel VBA unexpected truncation

Posted by: admin May 14, 2020 Leave a comment

Questions:

So I’ve spent the better part of the day debugging my VBA Class module and came upon a worrying phenomenon.

On the main spread sheet I have a cell formatted as “currency”, with 9 decimal place precision. In my VBA class, I have an attribute (a double) which takes on that cell value upon instantiation. i.e.,

myClass.loanDefault_7 = Range("loanDefaults")(1,7)

However, when I check the value stored in myClass.loanDefault_7 after the assignment, it has only 4 decimal place precision.

My question is why is VBA automatically (without my permission) truncating down this value? I want to understand why this happens, and how I can prevent it in the future.

Any help is much appreciated!

How to&Answers:

Try using the Value2 property instead:

myClass.loadDefault_7 = Range("loadDefaults")(1,7).Value2

From MSDN:

The only difference between this property and the Value property is that the Value2 property doesn’t use the Currency and Date data types. You can return values formatted with these data types as floating-point numbers by using the Double data type.

It seems that the Value property will automatically coerce the value into a Currency data type (which, AFAIK, is only capable of representing 4 numbers to the right of the decimal point).