Home > Software design >  Prevent MS-Word application from running auto macro when opening a Word document
Prevent MS-Word application from running auto macro when opening a Word document

Time:11-02

I have a code in my excel file which opens a certain Word document to read data from, and that Word document also has an "Document_Open" event handler (Which Shows a UserForm every time I open that Word document).

My Problem is that every time I run my Excel code to open up that Word file due to that "Document_Open" event handler, control of the code stuck in Word environment.

My code so far:

Private Sub CommandButton18_Click()

Dim Word As New Word.Application
Dim MRpt As Word.Document

Word.Visible = True
Set MRpt = Documents.Open(Filename:="MyWordDocumentPath" &".docm")

'At This Point code will be stuck because my UserForm inside my Word 
'document would show up and it prevents the code in Excel to continue)

End Sub

CodePudding user response:

Based on the article in https://wordmvp.com/FAQs/InterDev/DisableAutoMacros.htm, you can disable/enable auto macro by using WordBasic.DisableAutoMacros:

Private Sub CommandButton18_Click()
   Dim Word As New Word.Application
   Dim MRpt As Word.Document

   Word.Visible = True
   Word.WordBasic.DisableAutoMacros 1 'Disable
   Set MRpt = Documents.Open(Filename:="MyWordDocumentPath" &".docm")

   'At This Point code will be stuck because my UserForm inside my Word 
   'document would show up and it prevents the code in Excel to continue)

   Word.WordBasic.DisableAutoMacros 0 'Enable back
End Sub
  • Related