Can we use Conditional Compilation in VBA to declare variable inside a function?

Viewed 244

I have to refactor an old macro which are failing in newer MS-Office 365 version.

For kernel32 and User32 I have declared the function variable at the top like:

#If Vba7 Then 
  Declare PtrSafe Function lstrcpy Lib "kernel32" (ByVal lpString1 As Any, ByVal lpString2 As Any) As LongPtr
#Else
  Declare Function lstrcpy Lib "kernel32" (ByVal lpString1 As Any, ByVal lpString2 As Any) As Long
#EndIf 

But can I use conditional compilation inside the function as well like:

Function CopyToClipboard(ByVal Msg as String)
#If VBA7
Dim hWindow as LongPtr
#Else
Dim hWindow as Long
#End If
.
.
End Function

It's working in some system but copyToclipboard is still failing in some system. I have seen several copy clipboard function for VBA in StackOverflow but they are still failing in some system.

Any input would be greatly helpful as how to resolve this problem.

Update: What I ended up doing to fix the problem was I enclosed my declarations in the following condition handling both VBA7 and VBA6 and also 32-bit and 64-bit system using Win64 conditional argument.

#If Vba7 Then 
  #If Win64 Then
    Declare PtrSafe Function lstrcpy Lib "kernel32" (ByVal lpString1 As Any, ByVal lpString2 As Any) As LongPtr
  #Else
    Declare Function lstrcpy Lib "kernel32" (ByVal lpString1 As Any, ByVal lpString2 As Any) As Long
  #End If
#Else
  Declare Function lstrcpy Lib "kernel32" (ByVal lpString1 As Any, ByVal lpString2 As Any) As Long
#EndIf 

I copied the VBA6 declaration for 32-bit system because I think the LongPtr was not getting resolved properly and the macro was failing. Now its working perfectly in every system.

1 Answers

I recommend the following resources:

This works not only for declaration of functions (where it is mostly used) but also in normal code.

You can for example even use it for …

  • debuging modes like:

    #Const conDebug = 1   ' Declare public compilation constant in Declarations section. 
    
    Sub SelectiveExecution() 
        #If conDebug = 1 Then 
            ' Run code with debugging statements. 
        #Else 
            ' Run normal code. 
        #End If 
    End Sub
    
  • writing Mac/Windows specific code

    #If Mac Then 
        '. Place exclusively Mac statements here. 
    #ElseIf Win32 Then 
        '. Place exclusively 32-bit Windows statements here. 
    #Else 
        '. Place other platform/fallback statements here. 
    #End If
    
    

The example you showed is the perfect and correct way to go for this.


If you are not sure about your function declarations check the official reference:
Programming reference for the Win32 API.

Related