The four functions are:
The function takes a Double containing a value in the range of an unsigned Long and returns a Long that you can pass to an API that requires an unsigned Long.
The function takes an unsigned Long from an API and converts it to a Double for display or arithmetic purposes.
The function takes a Long containing a value in the range of an unsigned Integer and returns an Integer that you can pass to an API that requires an unsigned Integer.
The function takes an unsigned Integer from and API and converts it to a Long for display or arithmetic purposes.
Declare Function MyAPI Lib "xxx" (Value As Long) As Long
Dim uResult As Long
uResult = MyAPI(UnsignedToLong(3300000000))
Debug.Print "Return Code: " & LongToUnsigned(uResult)
In the above example, the MyAPI API accepts an unsigned Long as a parameter and returns an unsigned Long as a result code. Because VBA only understands signed Longs, the DECLARE statement uses signed Longs. The UnsignedToLong
function converts a number outside the range of signed Long (but within the
Without these functions, the input argument would have to have been specified as a signed Long, in this case -994967296, and the return value would have to be displayed as a signed value, possibly also as a negative number and non-intuitive.
Step by Step Example
- Create a new VBA project.
- Add the following code to a Module:
Private Const OFFSET_4 = 4294967296#
Private Const MAXINT_4 = 2147483647
Private Const OFFSET_2 = 65536
Private Const MAXINT_2 = 32767
Function UnsignedToLong(Value As Double) As Long
If Value < 0 Or Value >= OFFSET_4 Then Error 6 ' Overflow
If Value <= MAXINT_4 Then
UnsignedToLong = Value
UnsignedToLong = Value - OFFSET_4
Function LongToUnsigned(Value As Long) As Double
If Value < 0 Then
LongToUnsigned = Value + OFFSET_4
LongToUnsigned = Value
Function UnsignedToInteger(Value As Long) As Integer
If Value < 0 Or Value >= OFFSET_2 Then Error 6 ' Overflow
If Value <= MAXINT_2 Then
UnsignedToInteger = Value
UnsignedToInteger = Value - OFFSET_2
Function IntegerToUnsigned(Value As Integer) As Long
If Value < 0 Then
IntegerToUnsigned = Value + OFFSET_2
IntegerToUnsigned = Value
- Visual Basic only: Run the project and pause it.
- Type the following in the Immediate/Debug Window:
- You will get the following results:-994967296
Article ID: 189323 - Last Review: Mar 23, 2009 - Revision: 1