Home > Back-end >  Word AutoOpen for specific File
Word AutoOpen for specific File

Time:11-24

Is it possible to build something like AutoOpen but less generic? So I mean a macro, which executes when you open file xyz.docx.

CodePudding user response:

Please, copy the next code in "Normal.dotm" "ThisDocument" code module:

Option Explicit

Const docName =  "xyz.docx" 'use here the document name you need

Private Sub Document_Open()
   If ActiveDocument.Name = docName Then
       MsgBox ActiveDocument.Name & " has been opened..."
   End If
End Sub

The Open event is triggered for any document being open.

CodePudding user response:

Here's a sample macro that automatically runs when the document opens. This sample checks whether the user is trying to open a template for editing, then it creates a new document based on the template instead. (Bypass the macro by holding down Shift while you open the file).

This sample only makes sense when placed in a macro-enabled template, but you could also add something like this to a macro-enabled document. The document location would also have to be made a trusted location in Windows.

Sub AutoOpen()
    Dim PathTemp$, NameTemp$
    If ActiveDocument.Type = wdTypeTemplate Then
        NameTemp$ = ActiveDocument.Name
        PathTemp$ = ActiveDocument.Path
        Documents.Add Template:=PathTemp$ & Application.PathSeparator & NameTemp$
        For Each fWindow In Application.Windows
            If fWindow.Caption = NameTemp$ Then
                fWindow.Close SaveChanges:=wdDoNotSaveChanges
            End If
        Next fWindow
    End If
End Sub
  • Related