如何使用VBA查找和替换多个Word文档中的文本
我正在寻求帮助以查找和替换多个Word文档中的文本。我有一个代码只在一个文档中执行此操作,但不知道如何循环浏览同一文件夹中的所有文档。 代码如下:如何使用VBA查找和替换多个Word文档中的文本,vba,replace,ms-word,find,Vba,Replace,Ms Word,Find,我正在寻求帮助以查找和替换多个Word文档中的文本。我有一个代码只在一个文档中执行此操作,但不知道如何循环浏览同一文件夹中的所有文档。 代码如下: Sub storyrangesearch() For Each myStoryRange In ActiveDocument.StoryRanges With myStoryRange.Find .Text = " Of " .Replacement.Text = " o
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
子演示()
Application.ScreenUpdating=False
Dim STRFOLD作为字符串,strFile作为字符串,wdDoc
strFolder=GetFolder
如果strFolder=“”,则退出Sub
strFile=Dir(strFolder&“\*.doc”,vbNormal)
而strFile“”
设置wdDoc=Documents.Open(文件名:=strFolder&“\”&strFile,AddToRecentFiles:=False,可见:=False)
使用wdDoc
使用.Range.Find
.Text=“Of”
.Replacement.Text=“of”
.Format=False
.Forward=True
.MatchCase=True
.Wrap=wdFindContinue
.Execute Replace:=wdReplaceAll
以
.Close SaveChanges:=True
以
strFile=Dir()
温德
设置wdDoc=Nothing
Application.ScreenUpdating=True
端接头
函数GetFolder()作为字符串
作为对象的文件夹的尺寸
GetFolder=“”
文件夹集=CreateObject(“Shell.Application”)。浏览文件夹(0,“选择文件夹”,0)
如果(非oFolder为Nothing),则GetFolder=oFolder.Items.Item.Path
文件夹集=无
端函数
要将处理扩展到子文件夹,请参阅:It works。谢谢你的帮助。@LucasLiu:请看-