VBA Using Declare Imports that work on all versions of Office


Example

#If Vba7 Then
    ' It's important to check for Win64 first, 
    ' because Win32 will also return true when Win64 does.

    #If Win64 Then
        Declare PtrSafe Function GetFoo64 Lib "exampleLib32" () As LongLong
    #Else
        Declare PtrSafe Function GetFoo Lib "exampleLib32" () As Long
    #End If
#Else 
    ' Must be Vba6, the PtrSafe keyword didn't exist back then,
    ' so we need to declare Win32 imports a bit differently than above.

    #If Win32 Then
        Declare Function GetFoo Lib "exampleLib32"() As Long
    #Else
        Declare Function GetFoo Lib "exampleLib"() As Integer
    #End If
#End If

This can be simplified a bit depending on what versions of office you need to support. For example, not many people are still supporting 16 bit versions of Office. The last version of 16 bit office was version 4.3, released in 1994, so the following declaration is sufficient for nearly all modern cases (including Office 2007).

#If Vba7 Then
    ' It's important to check for Win64 first, 
    ' because Win32 will also return true when Win64 does.

    #If Win64 Then
        Declare PtrSafe Function GetFoo64 Lib "exampleLib32" () As LongLong
    #Else
        Declare PtrSafe Function GetFoo Lib "exampleLib32" () As Long
    #End If
#Else 
    ' Must be Vba6. We don't support 16 bit office, so must be Win32. 

    Declare Function GetFoo Lib "exampleLib32"() As Long
#End If

If you don't have to support anything older than Office 2010, this declaration works just fine.

' We only have 2010 installs, so we already know we have Vba7.

#If Win64 Then
    Declare PtrSafe Function GetFoo64 Lib "exampleLib32" () As LongLong
#Else
    Declare PtrSafe Function GetFoo Lib "exampleLib32" () As Long
#End If