pythonexcelwin32comkernel32pyxll

kernel32 library via excel com in Python


I would like to do the equivalent of the below Excel VBA code in Python - COM

Private Declare Function SetDllDirectory Lib "kernel32.dll" Alias "SetDllDirectoryA" ( _
    ByVal lpPathName As String) As Boolean

So now in Excel VBA, I can call SetDllDirectory(dllPath)

MSDN SetDllDirectory : http://msdn.microsoft.com/en-gb/library/windows/desktop/ms686203(v=vs.85).aspx

On the other hand, in Python, using win32com:

import win32com.client
xlapp = win32com.client.DispatchEx("Excel.Application") 

How can I do something like xlapp.SetDllDirectory(dllPath) (obviously this is invalid, hence this question)?

I have also tried ctypes.windll.kernel32.SetDllDirectoryA but this only sets the DLL Directory for Python, and not xlapp ( the Excel instance that is being manipulated by COM).

More Details: Essentially, I am doing this because I try to dynamically load XLL into Excel (xlapp.RegisterXLL ) . But this particular xll file requires a dll which resides in specific path. Therefore I would like the ability to set the DLL path.

Thanks a lot! Kris


Solution

  • Assuming your code is running in Excel using PyXLL, then setting the the path using os.environ should do what you need.

    os.environ["PATH"] += ";" + dllpath
    

    If you're just using win32com to get a currently running Excel application then it won't be so easy to change it's path, but maybe you could just bundle up the dll dependency into the same folder as the xll instead.