【发布时间】:2020-05-07 14:37:03
【问题描述】:
我想更新大量 Word 文件中的文本(在很多文件夹和子文件夹中)。我有一个函数可以遍历所有这些。
我想在整个文档中查找和替换。我可以看到文件正在打开和关闭,但最后什么都没有保存。
Sub UpdateOneFolderToUnicode()
Dim strFolder As String, strFile As String
strFolder = "my folder here"
If strFolder = "" Then Exit Sub
'strFile = Dir(strFolder & "\*.docx", vbNormal) ' for docx files
strFile = Dir(strFolder & "\*.doc", vbNormal)
While strFile <> ""
updateOneFile strFolder & "\" & strFile
strFile = Dir()
Wend
End Sub
Sub updateOneFile(filePath)
Dim wdDoc As Document
Application.ScreenUpdating = True
On Error GoTo UpdateErr
Set wdDoc = Documents.Open(FileName:=filePath, AddToRecentFiles:=False, Visible:=False)
With wdDoc
With .Range.Find
.Text = "~"
.Replacement.Text = ChrW(625)
.Wrap = wdFindContinue
.MatchCase = True
End With
.Range.Find.Execute Replace:=wdReplaceAll
End With
wdDoc.Close SaveChanges:=True
Set wdDoc = Nothing
Application.ScreenUpdating = True
Exit Sub
UpdateErr:
Debug.Print "Update file: " & filePath & " Error: " & Err.Description
Set wdDoc = Nothing
End Sub
【问题讨论】:
-
您没有收到任何错误?如果您在
Close行设置断点并查看文档是否有任何更改?如果您将wdDoc.Save放在wdDoc.Close之前,会有所不同吗?如果您将Find.Execute行更改为Debug.Print .Range.Find.Execute(Replace:=wdReplaceAll),它会将True或False放在VBA 编辑器的即时窗口中吗?