title: VBA FreeLibrary doesn't unload DLL
body: <p>I need to delete a DLL file when I am done using it (cleanup after code is completed). </p>
  
  <p>I try using "LoadLibrary" and "FreeLibrary" in Excel VBA but no matter what I do Excel.exe clings to the DLL file.</p>
  
  <pre><code> Public Declare PtrSafe Function FreeLibrary Lib "kernel32" (ByVal hLibModule As Long) As Long
   Public Declare PtrSafe Function LoadLibrary Lib "kernel32" Alias "LoadLibraryA" (ByVal lpLibFileName As String) As Long
  
   Private Sub Load_Unload_DLL()
  
       Dim lb As Long, pa As Long
       lb = LoadLibrary("C:\Users\Administrator\Documents\MathLibrary.dll")
  
       'MsgBox "Library address: " &amp; lb
  
       Dim FreeResult As Long
       FreeResult = 1
  
       Do Until FreeResult = 0
           FreeResult = FreeLibrary(lb)
       Loop
  
       Name "C:\Users\Administrator\Documents\MathLibrary.dll" As "C:\Users\Administrator\Documents\MathLibrary2.dll"
  
       Kill ("C:\Users\Administrator\Documents\MathLibrary2.dll")
  
   End Sub
  </code></pre>
  
  <p>Despite "FreeResult" equaling "0" I receive the following error when executing the "Kill" command:</p>
  
  <p><a href="https://i.stack.imgur.com/z8ptI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/z8ptI.png" alt="Path Access Error"></a></p>
  
  <p>And Process Explorer showing that the DLL file is indeed still loaded by Excel:</p>
  
  <p><a href="https://i.stack.imgur.com/2J8py.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2J8py.png" alt="Process Explorer"></a></p>
  
  <p>The file can be renamed, but not deleted (as indicated by the code).</p>
  
  <p>Am I missing something?</p>