Misunderstanding Long Data Type in VBA

The following examples are provided from the VBA overflow error help:

Dim x As Long
x = 2000 * 365 ' gives an error

Dim x As Long
x = CLng(2000) * 365 ' fine

I would think that since it is assumed that the Long data type can contain 32-bit numbers, the first example will work fine.

I ask about this because I have code like this:

Dim Price as Long
Price = CLng(AnnualCost * Months / 12)

and this causes an overflow error when the AnnualCost is 5000 and the month is 12.

What am I missing?

+3
source share
3 answers

2000 365 - Integer. VBA 16- , 2 , 16-. , 16 , . , 32- , 32- . 16- , , , . , :

Dim Price as Long
Price = CLng(AnnualCost) * Months / 12
+12

, , . Long , .

, Integer. Long Integer, , , , Longs () , 32- . , .

+2

VBA ( ). , , , . ( : http://support.microsoft.com/kb/191713) Long - "&" :

Price = CLng(AnnualCost * Months / 12&)

12 . , , . .

Const lngMonths12_c as Long = 12
Price = CLng(AnnualCost * Months / lngMonths12_c)
+1
source

All Articles