vba - 尝试选择多个文档时如何解决运行时错误 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
解决方案
您正在尝试在搜索过程中保存并关闭文档。似乎这表现为查找对话框仍处于打开状态并阻止文档正确关闭,从而阻止加载下一个文档。尝试将保存和关闭移出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 在这里检查。)
推荐阅读
- node.js - 在 workbook.addImage 中的 excel.js 中下载 AWS S3
- javascript - Nextjs 动态页面路由:在页面变量中使用扩展运算符 [...example] 或 [[...example]] 的目的是什么?
- java - Java:cmd jdk和jre版本区别
- javascript - 移动设备上的多级手风琴导航
- docker - 在 Docker 中关闭 https
- javascript - 无效或意外的令牌
- python - 有没有一种有效的方法可以将连续增加的数据行分类为熊猫数据框中的一组
- visual-studio-code - VSCode 快捷键 Ctrl+Shift+e 呈现为未知而不是导航到资源管理器窗口
- c# - 在用户注册 ASP.NET CORE MVC 身份时检查电子邮件是否已经存在
- java - Flyway 验证失败异常并出现错误检测到已解决的迁移未应用于数据库