我们可以在VBA中使用条件编译在函数内声明变量吗?

问题描述 投票:0回答:1

我必须重构一个旧的宏,该宏在较新的 MS-Office 365 版本中失败。

对于 kernel32 和 User32,我在顶部声明了函数变量,如下所示:

#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 

但是我也可以在函数内部使用条件编译吗:

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

它在某些系统中工作,但

copyToclipboard
在某些系统中仍然失败。 我在 StackOverflow 中看到了几个 VBA 的复制剪贴板功能,但它们在某些系统中仍然失败。

任何意见对于如何解决此问题都会非常有帮助。

excel vba
1个回答
3
投票

我推荐以下资源:

这不仅适用于函数声明(主要使用它),也适用于普通代码。

例如,您甚至可以将其用于……

  • 调试模式如下:

    #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
    
  • 编写 Mac/Windows 特定代码

    #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
    
    

您展示的示例是完美且正确的方法。


如果您不确定函数声明,请查看官方参考:
Win32 API 编程参考

© www.soinside.com 2019 - 2024. All rights reserved.