Monday, December 03, 2007

Run a Automatic Macro in Word Document

Execute Word Macro on File Open

There are numerous instances where one stores the word document format as a Microsoft Word template. When the user opens the document (using the template), some macro needs to be executed. This can be achieved by RunAutoMacro Method of Word VBA

Sub Run_Macro_In_WordDocument()

Dim oWD As Word.Document
Set oWD = Documents.Add("c:\dcomdemo\")
oWD.RunAutoMacro wdAutoOpen

End Sub

Here a new document is open based on the template and once the document is open the AutoOpen macro is fired

RunAutoMacro Method can be used to execute an auto macro that's stored in the specified document. If the specified auto macro doesn't exist, nothing happens

On the other hand, if a normal macro (not auto open etc) needs to be executed, Run method can be used

Application.Run "Normal.FormatBorders"


  1. Where would you place the code for this? In the .dot template or elsewhere?


    1. K,
      you should paste this code in a separate vba project, provided
      c:\dcomdemo\ is a valid word document with a macro in it. hope dis will help

  2. The Selection keyword inside the macro is not invoked if called from a vb project, do I have to add anything sort of ActiveDocument or ActiveWindow before the keyword in the macro?
    Plz help
    P.S The macro is getting called with other codes


Share on Facebook
Related Posts Plugin for WordPress, Blogger...
Download Windows Live Toolbar and personalize your Web experience! Add custom buttons to get the information you care about most.