Consider the following VBA function:
Function castAndAdd(inputValue As Variant) As Variant
If IsNumeric(inputValue) Then
castAndAdd = CDbl(inputValue) + 4
Else
castAndAdd = inputValue
End If
End Function
Calling it from the immediate window gives this output:
?castAndAdd("5,7")
61
?castAndAdd("5, 7")
5, 7
Stepping through the "5,7" call, I find that IsNumeric("5,7")
returns true
. I was thinking that maybe it gives this result because in Europe a comma is used as a decimal separator; this result is odd because I'm in the United States, so my locale should determine that Excel only recognizes a period as a decimal separator, right?
Even if we set aside the Europe/US issue, the bigger problem is that CDbl("5,7") returns 57, so that CDbl("5,7") + 4
returns 61, not 9.7 as I would have expected if the comma is a decimal separator. Is this a bug, or am I just not understanding how to use CDbl()
?
CDbl (Function) Converts any expression to a Double. This function accepts any expression convertible to a Double, including strings. A runtime error is generated if expression is Null.
In VBA, “CDBL” stands for “Convert to Double.” This function converts the given number to a Double data type. Take a look at the syntax of the CDBL function. The expression is the value we are trying to convert to a Double data type.
The ISNUMERIC function is a built-in function in Excel that is categorized as an Information Function. It can be used as a VBA function (VBA) in Excel. As a VBA function, you can use this function in macro code that is entered through the Microsoft Visual Basic Editor.
The IsNumeric function returns a Boolean value that indicates whether a specified expression can be evaluated as a number. It returns True if the expression is recognized as a number; otherwise, it returns False. Note: If expression is a date the IsNumeric function will return False.
The comma is not recognized as decimal, but as thousands separator. The mechanism is not so smart to require that then at least three digits should follow, but essentially it strips any of the thousands separators in interpreting it as a number.
So even CDbl("4,5,,6,7")
would yield 4567 as a number. All this is true when the comma is the thousands separator. If, as in some European countries, the point is the thousands separator, then a similar thing will happen with points.
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