【问题标题】:How to find and replace content of Word?如何查找和替换Word的内容?
【发布时间】: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),它会将TrueFalse 放在VBA 编辑器的即时窗口中吗?

标签: vba ms-word


【解决方案1】:

没有错误。

我通过将部分代码更新为:

Set wdDoc = Documents.Open(FileName:=filePath, AddToRecentFiles:=False, Visible:=False)
Set myRange = wdDoc.Content

With myRange.Find
  .Text = "Ä"
  .Replacement.Text = ChrW(256)
  .Wrap = wdFindContinue
  .MatchCase = True
End With
myRange.Find.Execute Replace:=wdReplaceAll

基本上使用Content而不是Range,我必须将wdDoc.Conent放入一个变量中,否则仍然无法正常工作(不知道为什么)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-08
    • 1970-01-01
    • 1970-01-01
    • 2015-01-31
    • 2014-10-12
    • 2014-06-13
    • 2019-07-07
    • 1970-01-01
    相关资源
    最近更新 更多