我正在尝试创建一个宏,以便在多个 Word 文档中进行批量查找和替换。我在网上找到了这个宏,并对其进行了修改,但我一直收到运行时错误 (5174),提示找不到该文件(尽管它确实在文件夹中)。
此外,在我找到初始问题的解决方案后,我需要能够查找和替换页脚中的图片。
Sub ReplaceText()
Dim Directory As String
Dim FType As String
Dim FName As String
Directory = "C:\Users\pieria\Desktop\TempPics"
FType = "*.docx"
ChDir Directory
FName = Dir(FType)
' for each file you find, run this loop
Do While FName <> ""
' open the file
Documents.Open FileName:=FName '<--Error is supposedly here
' search and replace the company name
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "CompanyA"
.MatchCase = True
.Replacement.Text = "CompanyB"
End With
Selection.Find.Execute Replace:=wdReplaceAll
' save and close the current document
ActiveDocument.Close wdSaveChanges
' look for next matching file
FName = Dir
Loop
End Sub
答案1
答案2
这是一个潜在的答案,它旨在方便用户使用:
Public Sub MassReplace()
Dim strPath As String
Dim strFile As String
Dim FType As String
Dim FName As String
Dim strFind As String
Dim strReplace As String
Dim WordApp As Object
Dim WordDoc As Object
'上面的文字定义了你的对象
strFind = InputBox("Enter Text to find")
strReplace = InputBox("Enter replacement Text")
' 用户使用输入框定义他们想要查找和替换的文本
With Application.FileDialog(msoFileDialogFolderPicker)
If .Show Then
strPath = .SelectedItems(1)
Else
MsgBox "No folder selected!", vbExclamation
Exit Sub
End If
End With
If Right(strPath, 1) <> "\" Then
strPath = strPath & "\"
strFile = Dir(strPath & "*.docx*")
End If
Application.ScreenUpdating = False
'上面的代码块允许用户选择要搜索的文件夹文件
Do While strFile <> "" 'Do this while strFile is not blank
Set WordApp = CreateObject("Word.Application") 'Open MS word
WordApp.Visible = True 'Make word visible
Set WordDoc = WordApp.Documents.Open(strPath & strFile) 'open file in folder
WordApp.ActiveDocument.Range.Select ' select all text
With WordApp.Selection.Find 'Using the find function allows a search of text
.Text = strFind 'find "strFind"
.Replacement.Text = strReplace 'replacement text is "strReplace"
.Wrap = wdFindContinue
'.Format = False
'.MatchCase = False
'.MatchWholeWord = False
'.MatchWildcards = False
'.MatchSoundsLike = False
.Execute Replace:=wdReplaceAll 'replace all text
WordApp.ActiveDocument.Close wdSaveChanges 'Close document and save changes
End With 'End with block
WordApp.Quit 'Close the word application
strFile = Dir 'Go back to the directory
Loop
Application.ScreenUpdating = True
End Sub
这似乎对 Word 2016 很有效。它允许用户定义文件路径并使用输入框定义要替换/查找的文本。要替换数字而不是文本,请将 strFind 和 strReplace 定义为整数(或其他数字类型)而不是文本。祝您编码愉快!