如何使我的 VBA 宏在打开 Word 文档时自动运行,而无需从开发人员功能区或按钮启动宏?
到目前为止,我尝试过这个,但它对我不起作用:
当我运行“FindChar”子程序时,它运行良好。我没有收到任何错误消息。看来脚本没有运行。
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
Run Code Online (Sandbox Code Playgroud)