【问题标题】:Running Word macro automatically when word document opened打开word文档时自动运行Word宏
【发布时间】:2021-07-15 15:05:04
【问题描述】:

如何让我的 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

【问题讨论】:

  • 不工作 不是很有帮助。你的代码被触发了吗?有什么事吗?您收到错误消息吗?直接调用而不是通过 Open-Event 调用时,FindChar-routine 是否正常工作?
  • FindChar 在我运行时运行良好。我没有收到任何错误消息。脚本似乎没有运行。
  • 在事件触发器中添加类似Debug.Print "Document-Open triggered" 的语句,并检查是否有内容写入即时窗口。您的代码在哪里?您需要将Document_open()-routine 放入 Document-module
  • 您到底在哪里有 Document_Open 子?

标签: vba ms-word


【解决方案1】:

Document_Open 宏仅在位于“ThisDocument”代码模块中时才有效。如果您的代码不存在,请将 Document_Open 更改为 AutoOpen

【讨论】:

  • 当我将代码移动到“ThisDocument”代码模块而不是Module1 时完美运行。谢谢!
  • 另外,“将Document_Open更改为AutoOpen”是什么意思?写private sub AutoOpen()而不是我写的?
  • 他的意思是宏的名称必须是“AutoOpen”而不是“Document_Open”才能在标准模块中工作。这个文档很特别。
猜你喜欢
  • 2021-12-15
  • 1970-01-01
  • 2022-01-06
  • 1970-01-01
  • 2015-04-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多