我正在尝试创建一个宏,以打开指定文件夹(及其所有子文件夹)中的所有.docx文件,并将“ strFindText1”变量中包含的文本替换为“ strReplaceText1”中的文本。
我在线找到了一个示例代码,并根据需要对其进行了修改,但是在“ .HomeKey单元:= wdStory”行中显示错误“对象不支持此属性或方法”。我无法解决。请帮助我。
statuspass
我应该指定我将从Excel文件运行宏以修改所有Word文件。
答案 0 :(得分:0)
您的代码存在多个问题。例如,您指定:
Dim objDoc As Document
,但是没有迹象表明您使用的是早期绑定还是后期绑定;您甚至没有一行引用Word应用程序。如果您使用的是早期绑定,我希望看到类似以下的内容:
Dim wdApp As New Word.Application, wdDoc as Word.Document
对于后期绑定,我希望看到类似的东西:
Dim objWord as Object, objDoc As Object
再加上代码以实例化Word。然后,您可以使用以下任一方法:
Set wdDoc = wdApp.Documents.Open(Filename:=strFolder & "\" & strFile)
或:
Set objDoc = objWord.Documents.Open(Filename:=strFolder & "\" & strFile)
视情况而定。
此外,可以改善您的文档处理代码。例如,您可以替换所有:
With objDoc
With Selection
.HomeKey Unit:=wdStory
With Selection.Find
.Text = strFindText1
.Replacement.Text = strReplaceText1
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
End With
objDoc.Save
objDoc.Close
具有:
With objDoc
With .Range.Find
.Text = strFindText1
.Replacement.Text = strReplaceText1
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute Replace:=2 'wdReplaceAll
End With
.Close True
End With
有关入门的一些代码,请尝试:
Sub BulkFindReplace()
'Note: this code requires a reference to the Word object model.
'See under the VBE's Tools|References.
Dim wdApp As New Word.Application, wdDoc As Word.Document
Dim strFolder As String, strFile As String, StrFnd As String, StrRep As String
strFolder = GetFolder
If strFolder = "" Then Exit Sub
StrFnd = ActiveWorkbook.Sheets("Sheet1").Range("C2").Value
StrRep = ActiveWorkbook.Sheets("Sheet1").Range("D2").Value
strFile = Dir(strFolder & "\*.docx", vbNormal)
While strFile <> ""
Set wdDoc = wdApp.Documents.Open(Filename:=strFolder & "\" & strFile, AddToRecentFiles:=False, Visible:=False)
With wdDoc
With .Range.Find
.Text = StrFnd
.Replacement.Text = StrRep
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute Replace:=wdReplaceAll
End With
.Close SaveChanges:=True
End With
strFile = Dir()
Wend
wdApp.Quit
Set wdDoc = Nothing: Set wdApp = Nothing
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