M Darblade M Darblade - 5 months ago 40
C++ Question

Close access to a dll in Excel

I'm currently working on a project using C++ and Excel. I made a DLL to export a C++ function in Excel. My problem is that when I test my function in Excel and I want to modify my DLL, I need to quit Excel because it's still running the .dll file, and Visual studio C++ can't delete the previous DLL to make an other.

It's a bit annoying to close and launch again Excel everytime so I would like to know if there is a way to close access to the Dll when the VBA script is finished.


Answer Source

One method you could use is to run a separate excel instance and automate opening/closing excel like so... (this is pseudocode I typed it in browser)

Sub TestMyDll()
  Dim xl as New Excel.Application
  xl.Workbooks.Open "file"
  xl.Run "MyFunctionCall"
  xl.Workbooks(1).Close False
  Set xl = Nothing
End Sub

A second method would be to dynamically load and unload the dll. This is probably the method I would use. As a test I copied Winhttp.dll to a different directory and called it my.dll. Do not put the dll in the same directory as the workbook containing your code or excel will probably load the 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
End Sub
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download