In the development of VBA, in order to be able to use functions provided by the system or functions developed in C ++, This article summarizes the call of C ++ DLL by VBA.
1. function declaration
Function prototype:
Dword winapi GetCurrentDirectory (
_ In DWORD nBufferLength,
_ Out LPTSTR lpBuffer
);
The function declaration is as follows:
Public Declare Function GetCurrentDirectoryLib "kernel32" Alias "GetCurrentDirectoryA" (ByValnBufferLength As Long, ByVal lpBuffer As String) As Long
Public is used to declare functions that can be used for all other procedures in all modules. Private is used to declare functions that can only be used in modules that contain the declaration.
Lib contains the dynamic link library name or code Resource Name of the declared function.
Alias indicates that the called function has another name in the dynamic link library (DLL.
2. DLL location
The DLL file must be in one of the following three directories:
(1) Windows System directory: \ Windows \ system32
(2) Any directory indicated by path in DOS
(3) in Windows XP: C: \ Documentsand Settings \ % USERNAME % \ My Documents ents
In order for VBA to call functions in the DLL, The DLL must be placed in any of the above three positions.
There are two ways to solve this problem:
1. copy the DLL to any of the preceding three directories before calling the DLL function.
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. Change the current path of the current process.
For example, if the DLL and the current EXCEL file are placed in the same directory, the current path of the current process is set as follows:
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. After this setting, you can access the DLL. In this way, you do not need to copy the DLL to the system directory to facilitate program release.
3. Return Value
If the returned value is a string, you need to allocate memory space for the string before calling the function.
Public Declare Function GetCurrentDirectoryLib "kernel32" Alias "GetCurrentDirectoryA" (ByValnBufferLength As Long, ByVal lpBuffer As String) As Long
LpBuffer is the output parameter.
Example:
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