overflow error

S

SonnyMaou

why would i get an overflow error on this line:

MsgBox Trim(inv * 64)

when inv is only 671?
 
G

Greg Maxey

Try:
Sub Test()
Dim inv As Integer
inv = 671
MsgBox Trim(CLng(inv) * 64)

End Sub

and see the VB help file, subject "Trappable Errors"
 
J

JE McGimpsey

Because 671 * 64 = 42944, which is larger than the largest integer
(32767). VBA will cast the result as the largest of the two operands.
Since inv is presumably Dim'd as an integer and 64 fits into an integer,
VBA will cast the result as an integer. Hence the overflow.

There's almost never a need to use integers on modern computers (it can
actually waste processor cycles) - use long integers instead

Dim inv As Long

instead.

Alternatively, cast 64 as a long integer (&) or a double (#):

MsgBox Trim(inv * 64&)
 
J

JE McGimpsey

VBA Help - look at each data type:

For instance:
Long data type
A 4-byte integer ranging in value from -2,147,483,648 to
2,147,483,647. The ampersand (&) type-declaration character
represents a Long in Visual Basic.

and it's helpful to know:
type-declaration character
A character appended to a variable name indicating the variable's
data type.
 
S

SonnyMaou

JE said:
Because... Hence the overflow.

There's almost never a need to use integers on modern computers (it can
actually waste processor cycles) - use long integers instead

Dim inv As Long

instead.

Alternatively, cast 64 as a long integer (&) or a double (#):

MsgBox Trim(inv * 64&)

Thanks, JE... Great info and advice!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top