【发布时间】:2019-08-23 17:51:08
【问题描述】:
我正在使用 Excel VBA 在 Word 中打开文档。打开文档后,目标是搜索“InsuranceCompanyName”并将其替换为公司名称。
我试过了
wordDoc.Find.Execute FindText:="InsuranceCompanyName", ReplaceWith:="Fake Ins Co"
和
wordDoc.Replace What:="InsuranceCompanyName", Replacement:="Fake Ins Co"
还有
For Each myStoryRange In ActiveDocument.StoryRanges
With myStoryRange.Find
.Text = "InsuranceCompanyName"
.Replacement.Text = "Fake Ins Co"
.WrapText = wdFindContinue
.Execute Replace:=wdReplaceAll
End With
Next myStoryRange
下面列出了完整的代码。
Sub FindReplace()
Dim wordApp As Object
Dim wordDoc As Object
Dim myStoryRange As Range
'sets up the word app
Set wordApp = CreateObject("Word.Application")
wordApp.Visible = True
'opens the document that we need to search through
Set wordDoc = wordDoc = wordApp.Documents.Open("C:\Users\cd\LEQdoc.docx")
'here is where the find and replace code would go
End Sub
对于第一种方法,我得到了错误:
对象不支持此属性或方法。
第二个:同样的错误
第三种方法:
参数不是可选的
关于.Find in
With myStoryRange.Find
【问题讨论】:
-
Set wordDoc = wordDoc = wordApp.Documents.Open("C:\Users\cd\LEQdoc.docx")应该是Set wordDoc = wordApp.Documents.Open("C:\Users\cd\LEQdoc.docx") -
ActiveDocument不是 Excel 概念,因此您需要在前面加上wordApp即wordApp.ActiveDocument -
还要确保声明常量
wdFindContinue、wdReplaceAll等,因为您是后期绑定 MS Word -
@SiddharthRout - 快!
-
将
Dim myStoryRange As Range更改为Dim myStoryRange As Object