你可以使用的一种方法是运行一个单独的excel实例并像这样自动打开/关闭excel ...(这是我在浏览器中输入的伪代码)
Sub TestMyDll()
Dim xl as New Excel.Application
xl.Workbooks.Open "file"
xl.Run "MyFunctionCall"
xl.Workbooks(1).Close False
xl.Quit
Set xl = Nothing
End Sub
第二种方法是动态加载和卸载dll . 这可能是我会使用的方法 . 作为测试,我将Winhttp.dll复制到另一个目录并将其命名为my.dll . 不要将dll放在与包含代码的工作簿相同的目录中,否则excel可能会加载dll .
Option Explicit
Private Declare Function FreeLibrary Lib "kernel32" (ByVal hLibModule As Long) As Long
Private Declare Function LoadLibrary Lib "kernel32" Alias "LoadLibraryA" (ByVal lpLibFileName As String) As Long
'my.dll is a copy of Winhttp.dll in a directory other than where this workbook is saved.
'Calling this will result in an error unless you call LoadLibrary first
Private Declare Function WinHttpCheckPlatform Lib "my.dll" () As Long
Private Sub Foo()
Dim lb As Long
lb = LoadLibrary("C:\Users\David\Downloads\my.dll")
MsgBox WinHttpCheckPlatform
'I found I had to do repeated calls to FreeLibrary to force the reference count
'to zero so the dll would be unloaded.
Do Until FreeLibrary(lb) = 0
Loop
End Sub