使用Macro / VBA查找和替换单词

时间:2019-02-18 16:44:48

标签: vba ms-word word-vba

我想更新许多Word文件(在许多文件夹和子文件夹中)中的某些文本。我有一个功能可以遍历所有这些。

我基本上想在整个文档中进行查找和替换。但是我无法进行查找和替换工作。我可以看到文件正在打开和关闭,但是最后什么也没保存。

我有一个宏/ VBA代码来更新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

1 个答案:

答案 0 :(得分:0)

没有错误。

我将部分代码更新为:

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放入变量中,否则仍然无法正常工作(不确定原因)。