我想知道如何在vba中声明和使用dll。我有一个用C编写的代码,我想用excel表格中的一些数据来测试我的C代码。怎么可能?
多谢提前

最佳答案

必须在VBA模块中声明函数:
对于命令:

[Public | Private] Declare Sub name Lib "libname" [Alias "aliasname"] [([arglist])]

对于函数调用:
[Public | Private] Declare Function name Lib "libname" [Alias "aliasname"] [([arglist])] [As type]

我的一个应用程序中有几个示例:
Public Declare Function apiGetUserName Lib "advapi32.dll" Alias _
    "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long
Public Declare Function WM_apiGetDeviceCaps Lib "gdi32" Alias _
    "GetDeviceCaps" (ByVal hdc As Long, ByVal nIndex As Long) As Long
Declare Function WM_apiGetDesktopWindow Lib "user32" Alias _
    "GetDesktopWindow" () As Long
Declare Function WM_apiGetDC Lib "user32" Alias _
    "GetDC" (ByVal hwnd As Long) As Long
Declare Function WM_apiReleaseDC Lib "user32" Alias _
    "ReleaseDC" (ByVal hwnd As Long, ByVal hdc As Long) As Long
Declare Function WM_apiGetSystemMetrics Lib "user32" Alias _
    "GetSystemMetrics" (ByVal nIndex As Long) As Long
Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" _
    (ByVal lpBuffer As String, nSize As Long) As Long

编辑以添加PtrSafe信息:
MSDN PtrSafe Language Reference
在64位版本的Office Declare语句中运行时,必须包含PtrSafe关键字。PtrSafe关键字断言Declare语句可以安全地在64位开发环境中运行。向Declare语句中添加PtrSafe关键字仅表示Declare语句显式地以64位为目标,语句中需要存储64位(包括返回值和参数)的所有数据类型仍必须修改为使用64位积分的长整数或指针和句柄的长ptr保存64位数量。

10-07 17:14