Calculations

Using the "*" and "+" operators can return Overflow Run-Time Error.

link - https://stackoverflow.com/questions/17315650/overflow-when-multiplying-integers-and-assigning-to-long 

Dim myLong As Long 
Debug.Print TypeName(24) '= Integer
Debug.Print TypeName(60) '= Integer
Debug.Print TypeName(60) '= Integer
myLong = 24 * 60 * 60 ' Overflow

The literals 24, 60, and 60 are all of type Integer so by default, the * operator returns an Integer, which overflows because the result is greater than 32,767.


Debug.Print TypeName(32767)     '= Integer  
Debug.Print TypeName(1) '= Integer
myLong = 32767 + 1 ' Overflow.

The literals 32767 and 1 are all of type Integer so by default, so the + operator returns an Integer, which overflows because the result is greater than 32,767.


Debug.Print TypeName(32768)     '= Long  
Debug.Print TypeName(1) '= Integer
myLong = 32768 + 1 ' Works fine!

The literal 32768 is a Long by default, so the * operator returns a Long, so there is no overflow.


© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext