运行 word文档打开时自动生成word宏

Running Word macro automatically when word document opened

如何在打开 Word 文档时自动创建 VBA 宏 运行ning,而无需从开发人员功能区或按钮启动宏?

到目前为止我已经尝试过了,但它对我不起作用:

“FindChar”子在我 运行 时运行良好。我没有收到任何错误消息。脚本似乎不是 运行ning.

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

一个Document_Open宏只有在'ThisDocument'代码模块中才有效。如果您的代码不存在,请将 Document_Open 更改为 AutoOpen