当前位置:编程学习 > VB >>

VBA调用C/C++ DLL

 

在VBA开发过程中,为了能够使用系统已经提供的函数,或已经用C++语言开发的功能,本文对VBA调用C++ DLL进行了总结。

 

1.        函数声明

 

Function prototype:

 

DWORD WINAPI GetCurrentDirectory(

 

 __in   DWORD nBufferLength,

 

 __out  LPTSTR lpBuffer

 

);

 

函数声明如下:

 

Public Declare Function GetCurrentDirectoryLib "kernel32" Alias "GetCurrentDirectoryA" (ByValnBufferLength As Long, ByVal lpBuffer As String) As Long

 

Public  用于声明对所有模块中的所有其它过程都可以使用的函数。  Private   用于声明只能在包含该声明的模块中使用的函数。 

 

Lib包含所声明函数的动态链接库名或代码资源名。   

 

Alias 表示将被调用的函数在动态链接库(DLL)   中还有另外的名称。

 

 

 

2.        DLL的位置

 

DLL文件必须位于以下三个目录之一:

 

(1)Windows的系统目录:\Windows\system32

 

(2)DOS中path所指出的任何目录

 

(3)Windows XP系统下:C:\Documentsand Settings\%USERNAME%\My Documents

 

为了VBA可以调用DLL中的函数,必须把DLL放在以上三个位置中的任何一个。

 

有两种办法可以解决这个问题:

 

1.      在调用DLL 函数之前,把DLL copy到以上三个目录中的任何一个。

 

Dim fso AsObject

 

Dim dllFileNameAs String

 

dllFileName = Environ("SYSTEMROOT")+ “\system32\LicenseVerify.dll”

 

Set fso =CreateObject("Scripting.FileSystemObject")

 

Iffso.FileExists(dllFileName) = False Then

 

fso. CopyFile ThisWorkbook.Path + “\ LicenseVerify.dll”,dllFileName

 

End If

 

 

 

2.      改变当前进程的当前路径。

 

例如,DLL与当前EXCEL文件放在同一个目录下,这个时候当前进程的当前路径设置如下:

 

Public Declare Function SetCurrentDirectoryLib "kernel32" Alias "SetCurrentDirectoryA" (ByVallpPathName As String) As Long ‘ function declaration

 

SetCurrentDirectory (ThisWorkbook.Path) ‘set the current directory to Thisworkbook.Path

 

OK,这样设置后,就可以访问DLL了。这样方便程序的发布,不需要用户把DLL复制到系统目录下。

 

 

 

3.        返回值

 

如果返回值是字符串,需要在函数调用前为字符串分配内存空间。

 

Public Declare Function GetCurrentDirectoryLib "kernel32" Alias "GetCurrentDirectoryA" (ByValnBufferLength As Long, ByVal lpBuffer As String) As Long

 

其中,lpBuffer 是输出参数。

 

例子:

 

Public Declare Function GetCurrentDirectoryLib "kernel32" Alias "GetCurrentDirectoryA" (ByValnBufferLength As Long, ByVal lpBuffer As String) As Long

 

 

 

Private Sub DoVerify()

 

    Dimresult As Integer

 

    Dim retValue AsString

 

 

 

    retValue = String(1024, vbNullChar) 'allocate the buffer for out parameter.

 

 

    result= GetCurrentDirectory(1024, retValue)   

 

End Sub

补充:软件开发 , C++ ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,