Sub TestFunction()
Dim var As Double
var = 25 * 24 * 23 * 22 * 21 * 20
End Sub
I am receiving an overflow error for this vba operation. when i run it in a cell with functions i get 127,512,000
what could possibly be an error for this? this should be well below the size limit for this data type right?
VBA annoyingly converts the first term to an Integer because in your case, it is small enough.
Amend this line, that it is converted explicitly to a double:
var = CDbl(25) * 24 * 23 * 22 * 21 * 20
Try it like this:
The problem in your case is that when VBA tries to sum numbers it has its own logic, going through Integer first and then parsing it to the number on the left. If the first number is bigger than integer (32767) or is explicitly converted as a
Double
,Long
,Single
, then it is ok. Here you will not have any problems, because43333
is automatically converted tolong
and it is ok:In your case, if the first number is
25.1
, instead of25
, it gets automatically converted to double, thus later you will not have problems, as far asDouble*Integer = Double
Going a little deeper, using the
VarType()
function. Declarek
as Variant, and see what VBA converts it to, depending on its values and the mathematic operation:All
debug.print
returnTrue
.