0
votes

How can I make my VBA macro running automatically when the Word document is opened, without starting the macro from the developer ribbon or a button?

so far I tried this and it isn't working for me:

"FindChar" sub is working well when I run it. I'm not getting any error messages. It seems the script isn't running.

Private Sub Document_open()

   Call FindChar

End Sub

Sub FindChar()

   Dim oTbl As Table
   Dim stT As Long, enT As Long
   Dim stS As Long, enS As Long

   With Selection.Find             ' Replacement
      .Text = "["
      .Replacement.Text = ""
      .Forward = True
      .Wrap = wdFindContinue
   End With

   For Each oTbl In ActiveDocument.Tables

    If oTbl.Shading.BackgroundPatternColor = RGB(176, 255, 137) Then 
    
        oTbl.Columns(1).Select

        Do While Selection.Find.Execute

            stT = oTbl.Range.Start                    
            enT = oTbl.Range.End

            stS = Selection.Range.Start               
            enS = Selection.Range.End

            If stS < stT Or enS > enT Then Exit Do

            Selection.Collapse wdCollapseStart
            Selection.Find.Execute Replace:=wdReplaceOne
            
        Loop
        Selection.Collapse wdCollapseEnd
    
    End If
    
Next

End Sub
1
Isn't working is not very helpfull. Is your code triggered at all? Is something going wrong? Do you get an error message? Is the FindChar-routine working correctly when call directly and not via the Open-Event?FunThomas
FindChar is working well when I run it. I'm not getting any error messages. It seems the script isn't running.User1
Put a statement like Debug.Print "Document-Open triggered" in the event trigger and check if something was written to the Immediate Window. Where is your code located? You need to put the Document_open()-routine in the Document-moduleFunThomas
Where exactly do you have the Document_Open sub?norie

1 Answers

3
votes

A Document_Open macro only works when it's in the 'ThisDocument' code module. If your code isn't there, change Document_Open to AutoOpen