如何解决如何使用 VBA 在多个 Word 文档中查找和替换文本
我正在寻求帮助以查找和替换多个 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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。