Monday, June 26, 2006

Running Word VBA Macros from VB (OLE)

The other day I needed to kickoff a Microsoft Word template macro from inside a VB app. There's surprisingly little information out there on this subject. Here's my solution:Private Sub mnuFileProcess_Click() Dim oWord As Object 'create the Word object Set oWord = CreateObject("Word.Application") ' make Word visible oWord.Visible = True 'enable a template On Error GoTo handler oWord.AddIns("c:\vba\mymacros.dot") _ .Installed = True On Error GoTo 0 run: 'run a macro oWord.run "Module1.Main" oWord.Quit Set oWord = Nothing Exit Sub handler: 'load template from scratch oWord.AddIns.Add _ FileName:="c:\vba\mymacros.dot", Install:=True Resume run End Sub

Note that this code can either enable a loaded template or install a template from any location. The template doesn't need to be loaded when Word starts. First it tries to install (enable) a loaded template with this line:

oWord.AddIns("c:\vba\mymacros.dot") _ .Installed = True

If this fails control passes to the error handler which then adds the template and sets its installed state to true with this code:

oWord.AddIns.Add FileName:= _ "c:\vba\mymacros.dot", Install:=True
 

0 Comments:

Post a Comment

<< Home