Solved Why an overflow? (1 Viewer)

Gasman

Enthusiastic Amateur
Local time
Today, 00:19
Joined
Sep 21, 2011
Messages
17,428
TRying to help someone on another forum, they were getting overflow when assigning 4692 * 283 to a Long variable.

As you can see from my reply, I could also get that issue, but found a way around it.

Why would this happen? Just curious really?

-----------------------------------------------------
4692*283 = 1,327,836
That still gives me error 6?

Code:
Sub TestLong()
Dim lngResult As Long
Dim i1 As Integer, i2 As Integer
i1 = 4692
i2 = 283
lngResult = i1 * i2 'Errors here
Debug.Print lngResult


End Sub
yet Long is supposed to be able to contain -2,147,483,648 to 2,147,483,648

If I use lngResult = 2147483640, it accepts it no problem?

This works
Code:
Sub TestLong()
Dim lngResult As Long
Dim i1 As Long, i2 As Long
i1 = 4692
i2 = 283
lngResult = i1 * i2
Debug.Print lngResult


End Sub
 
Thank you CJ.
 
change on of the values to long, making the calculation long.

? 4692 * clng(283)
1327836
 
If you look at my post, that is what I did, but curious to know why.
In your original expression both operands are of short integer data type. Multiplying the two values tries to return another value of short integer type, but in this case the product of the two values is beyond the capability of a short integer data type, hence the overflow. Even though you attempted to assign the result to a variable of long integer data type, the overflow has already occurred before the assignment takes place. Making at least one of the operands a value of long integer data type avoids the overflow because this causes the expression to return a value of long integer data type.
 
So one can get by with just setting one of them to Long?, not having to set both?
 
The technical term used by VBA is "LET-Coercion" and it relates to making (coercing) the expression's implied internal variable to become large enough to hold a PREDICTED datatype. The compiler sees two INTEGER variables and so predicts an INTEGER result because it doesn't do a "look-ahead" of the values to check for overflow. (In the general case, the compiler CAN'T look ahead.)

Make either variable LONG or use CLNG() around either INTEGER and the compiler recognizes the presence of a LONG in the computation so coerces everything to be long enough for that. Unless you have a 64-bit version of Office, LONG is the highest possible integer coercion, after which your next step would end up with DOUBLE. Never tried a case that would have gone to LONGLONG because I don't use 64-bit Office.
 

Users who are viewing this thread

Back
Top Bottom