簡體   English   中英

如何使用 VBA 在多個 Word 文檔中查找和替換文本

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

我正在尋求幫助以查找和替換多個 Word 文檔中的文本。 我有一個代碼只在一個文檔中執行此操作,但不知道如何遍歷同一文件夾中的所有文檔。 這是代碼:

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

例如:

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

要將處理擴展到子文件夾,請參閱: https://www.msofficeforums.com/117894-post9.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM