首页 > 解决方案 > 尝试选择多个文档时如何解决运行时错误 5479?

问题描述

我试图编写一个宏来查找一个单词并为其添加书签,并为多个文档、所有文档中的相同单词和相同书签执行此操作。但是,如果我选择多个文档,我会收到一条错误消息:

运行时错误 5479
您无法关闭 Microsoft Word,因为对话框已打开。

我单击确定,切换到 Word,然后关闭对话框。我在 Windows 7 上运行的 Word 2013 中运行它。

我希望它打开每个 Word 文档,找到术语“TBC”,添加书签 UMR,然后保存并关闭文档,然后它会打开下一个文档并执行相同操作,直到文档用完。

实际发生的是它改变了第一个,然后我得到了运行时错误。当我点击调试时突出显示的行是:

documents.Open dlgFile.SelectedItems (nDocx)

这是我的VBA:

Private Sub CommandButton1_Click()
  Dim myRange As Range
  Set dlgFile = Application.FileDialog(msoFileDialogFilePicker)

  With dlgFile
    dlgFile.AllowMultiSelect = True
    If .Show = -1 Then

      For nDocx = 1 To dlgFile.SelectedItems.Count

        Documents.Open dlgFile.SelectedItems(nDocx)
        MsgBox (ActiveDocument)
        Set objDocx = ActiveDocument

            Set myRange = ActiveDocument.Content
            With myRange.Find
                Do While .Execute(FindText:="TBC", MatchCase:=True)
                   ActiveDocument.Bookmarks.Add Name:="UMR", Range:=myRange
                   myRange.Select
                   objDocx.Save
                   objDocx.Close
                Loop
               End With
            Set objDocx = Nothing
       Next nDocx

Else
  MsgBox ("You need to select documents first!")
  Exit Sub

End If

  End With

  MsgBox ("You have added all the bookmarks.")


End Sub

标签: vbams-word

解决方案


您正在尝试在搜索过程中保存并关闭文档。似乎这表现为查找对话框仍处于打开状态并阻止文档正确关闭,从而阻止加载下一个文档。尝试将保存和关闭移出While循环:

For nDocx = 1 To dlgFile.SelectedItems.Count

  Documents.Open dlgFile.SelectedItems(nDocx)
  MsgBox (ActiveDocument)
  Set objDocx = ActiveDocument

  Set myRange = ActiveDocument.Content
  With myRange.Find
    Do While .Execute(FindText:="TBC", MatchCase:=True)
      ActiveDocument.Bookmarks.Add Name:="UMR", Range:=myRange
      myRange.Select
    Loop
  End With
  objDocx.Save
  objDocx.Close
  Set objDocx = Nothing
Next nDocx

(这在 Word 2016 中有效,但我的原始代码的行为确实略有不同 - 所有文档都保持打开状态,但没有运行时错误。我没有 2013 在这里检查。)


推荐阅读