简体   繁体   English

如何使用 VBA 在多个 Word 文档中查找和替换文本

[英]How to find and replace a text in multiple Word documents using VBA

I am seeking help to find and replace texts in multiple Word documents.我正在寻求帮助以查找和替换多个 Word 文档中的文本。 I have a code to do that in only one document but don't know how to loop through all documents in the same folder.我有一个代码只在一个文档中执行此操作,但不知道如何遍历同一文件夹中的所有文档。 Here is the code:这是代码:

Sub storyrangesearch()
    
For Each myStoryRange In ActiveDocument.StoryRanges
    With myStoryRange.Find
        .Text = " Of "
        .Replacement.Text = " of "
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = True
        .MatchWholeWord = True
        .MatchByte = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
        .Execute Replace:=wdReplaceAll
    End With
Next myStoryRange
End Sub

For example:例如:

Sub Demo()
Application.ScreenUpdating = False
Dim strFolder As String, strFile As String, wdDoc
strFolder = GetFolder
If strFolder = "" Then Exit Sub
strFile = Dir(strFolder & "\*.doc", vbNormal)
While strFile <> ""
  Set wdDoc = Documents.Open(FileName:=strFolder & "\" & strFile, AddToRecentFiles:=False, Visible:=False)
  With wdDoc
    With .Range.Find
      .Text = " Of "
      .Replacement.Text = " of "
      .Format = False
      .Forward = True
      .MatchCase = True
      .Wrap = wdFindContinue
    .Execute Replace:=wdReplaceAll
    End With
    .Close SaveChanges:=True
  End With
  strFile = Dir()
Wend
Set wdDoc = Nothing
Application.ScreenUpdating = True
End Sub
 
Function GetFolder() As String
Dim oFolder As Object
GetFolder = ""
Set oFolder = CreateObject("Shell.Application").BrowseForFolder(0, "Choose a folder", 0)
If (Not oFolder Is Nothing) Then GetFolder = oFolder.Items.Item.Path
Set oFolder = Nothing
End Function

To extend the processing to sub-folders, see: https://www.msofficeforums.com/117894-post9.html要将处理扩展到子文件夹,请参阅: https://www.msofficeforums.com/117894-post9.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM