Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically set DLL search path in VBA macro

Tags:

ms-word

vba

dll

The problem

  • I have a word template which uses VBA's Declare statement to link to a dll, whose path can be determined within the VBA macro
  • I want to delploy this to the users %APPDATA%\Microsoft\Word\STARTUP directory
  • I DON'T want to permanently change the user's PATH environment variable (temporarily would be OK, but this doesn't seem to work as they don't get refreshed until application restart)

Attempted solution

I tried dynamically adding the code with the Declare statements using ThisDocument.VBProject.CodeModule.AddFromString(code) which works when loading the template from a normal directory, but when the template is within Word\STARTUP, it gives the following error:

Run-time error '50289':

Can't perform operation since the project is protected.

And setting the registry key "HKEY___LOCAL_MACHINE\Software\Microsoft\Office\11.0\Word\Security\AccessVBOM" to 1 doesn't fix this when the template is in Word\STARTUP


I'm really struggling to find a solution. If anyone knows a way to do this, that would be great.

like image 825
Steve Ridout Avatar asked Jan 16 '09 11:01

Steve Ridout


1 Answers

You can use LoadLibrary api.

For example in my projects the code looks like this:

If LibraryLoaded() Then
   Call MyFunc ...
End If


Public Function LibraryLoaded() As Boolean

 Static IsLoaded As Boolean
 Static TriedToLoadAlready As Boolean

 If TriedToLoadAlready Then
    LibraryLoaded = IsLoaded
    Exit Function
  End If
  Dim path As String
 path = VBAProject.ThisWorkbook.path
 path = Left(path, InStrRev(path, "\") - 1)
 IsLoaded = LoadLibrary(path & "\bin\" & cLibraryName)
 TriedToLoadAlready = True

 LibraryLoaded = IsLoaded

End Function
like image 66
SparcU Avatar answered Oct 14 '22 14:10

SparcU