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

标签 excel vba

我必须重构在较新的 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 的复制剪贴板功能,但它们在某些系统中仍然失败。

任何输入都将对解决此问题有很大帮助。

更新: 我最终为解决该问题所做的是,我将我的声明包含在以下条件中,处理 VBA7 和 VBA6 以及使用 Win64 条件参数的 32 位和 64 位系统。

#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 

我复制了 32 位系统的 VBA6 声明,因为我认为 LongPtr 没有得到正确解析并且宏失败了。 现在它在每个系统中都能完美运行。

最佳答案

我推荐以下资源:

这不仅适用于函数声明(它最常用的地方),也适用于普通代码。

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

  • Debug模式如下:

    #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
    
    

您展示的示例是实现此目的的完美且正确的方法。


如果您不确定您的函数声明,请查看官方引用资料:
Programming reference for the Win32 API .

关于excel - 我们可以在 VBA 中使用条件编译来在函数内声明变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65301279/

相关文章:

charts - Excel VBA - 如何设置图表系列的线条样式?

vba - 您可以将 VBA 代码放在 Function 或 Sub 之外的裸模块中吗?

vba - 带双引号的 RegExp 模式中的编译错误

python - xlwings module.py 从 excel 调用 python

arrays - 在vba中连接两个数组?

vba - Excel VBA 将搜索(或使用查找)限制在单行或行范围内

vba - Excel VBA - 将一系列图表保存到一张 GIF 图片中以获得动画效果

vba - 将字符串和数字连接为数字

excel - 识别模式并提取子串

html - 使用 XMLHTTP 使用 vba 进行网页抓取