利用word VBA自动替换文件夹中所有文档里的指定内容
注意页眉页脚,与正文内容的替换方法不同
Sub replacement()
’ replacement Macro’ Application.ScreenUpdating = False
Dim myPath As String
Dim FileCount As Integer
Dim i As Integer
Dim myDoc As Document
Dim filename As String
Dim arr(100) As String
Dim headr As Word.HeaderFooter
‘替换页眉’
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = “选择目标文件夹”
If .Show = -1 Then
myPath =.SelectedItems(1)
Else
Exit Sub
End If
End With
filename = Dir(myPath & “*.doc”)
FileCount = FileCount + 1
arr(FileCount) = filename
Do While filename <> “”
filename = Dir
If filename ="" Then
Exit Do
End If
FileCount =FileCount + 1
arr(FileCount) =filename
Loop
For i = 1 To FileCount
Set myDoc =Documents.Open(myPath & “” & arr(i))
For Each headr In myDoc.Sections(1).Headers
With headr.Range.Find
.Text =“E2020”
.replacement.Text = “E2021”
.Executereplace:=wdReplaceAll, Forward:=True, Wrap:=wdFindStop
End With
Next headr
myDoc.Save
myDoc.Close
’ Macro 替换正文内容’ myDoc.Windows.Application.Activate’ Selection.Find.ClearFormatting’ Selection.Find.Replacement.ClearFormatting’ WithSelection.Find
’ .Text =“E2020”
’ .Replacement.Text = “E2021”
’ .Forward =True
’ .Wrap =wdFindContinue
’ .Format =False
’ .MatchCase =False
’ .MatchWholeWord = False
’ .MatchByte =False
’ .MatchWildcards = False
’ .MatchSoundsLike = False
’ .MatchAllWordForms = False
’ End With
’ Selection.Find.Execute replace:=wdReplaceAll
’ ActiveDocument.Save
’ ActiveWindow.Close
Set myDoc =Nothing
Next
Application.ScreenUpdating= True
End Sub
更多推荐



所有评论(0)