Is there a constant for max value for integer type?
Asked Answered
D

2

18

I'm searching for a constant like MAXINT in c, for VBA code. I found references only in other languages, and cannot find one for VBA.

If there is no such constant what is the maximum number an int in VBA can hold? I tried 2147483647 but got an overflow error.

Deviationism answered 15/6, 2016 at 13:30 Comment(8)
An Integer in VBA has maximum value of 32767 and minimum of -32768Fustanella
And for a Long, it's 2^31 - 1 = 2147483647. AFAIK, there are no constants for that.Retarder
It should be noted that since we aren't using 16-bit environments anymore, it almost never makes sense to use Integer over Long.Retarder
@Retarder If I understand you correctly, an Integer in VBA in my Win10 will always consume 4 bite?Mundane
@marlan: No. Integer = 2 bytes. But unless you create gigantic arrays, memory isn't really an issue anymore. Overflow is.Retarder
Here is a discussion (from today) on the topic in Visual C++, padding memory etc. VBA would not pad an Integer to 32bit?Mundane
@marlan: Heh, good question. I always took the 2 bytes for granted. I suggest you try it out, allocating large arrays and watching the memory usage with Process Explorer.Retarder
Ok @Retarder here are my results: Before running code, MS Access Process consumed 12.8~9 MB. When running Dim intArr(100000) As Integer Process consumed 13.1 MB. When running Dim lngArr(100000) As Long Process consumed 13.3 MB. The above was tested some 3 times. Conclusion: VBA doesn't pad integers in static integer arrays. As for combinations of ints and lngs, these are actually arrays of Variatns or Objects (=refferences), and it is tough to conclude…Mundane
R
27

VBA does not provide a MAXINT constant. But you can derive that value easily:

MAXINT = (2 ^ 15) -1
Debug.Print MAXINT
 32767

Or you could define it as a Public constant with this in the Declarations section of a standard module:

Public Const MAXINT As Integer = (2 ^ 15) - 1

Then MAXINT would be available for the rest of your VBA code in that application.

And for Long Integer, the maximum value is ...

MAXLONG = (2 ^ 31) -1
Debug.Print MAXLONG
 2147483647 
Rubi answered 15/6, 2016 at 13:43 Comment(0)
T
2

Since we are here,,,
lets complete the case and add a safety feature:

Dim MinInt As Integer
Dim MinLong As Long

MinInt = -2 ^ 15
MinLong = -2 ^ 31

Debug.Print MinInt, MinLong
     '     -32768  -2147483648
Tagmeme answered 8/6, 2022 at 15:44 Comment(1)
For us newbies, it would add interest to hear precisely why this achieves safety.Hoodmanblind

© 2022 - 2024 — McMap. All rights reserved.