excel - 如何使用 Excel VBA 在 Word 中查找和替换文本?
问题描述
我正在使用 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
解决方案
试试这个代码
Option Explicit
Const wdReplaceAll = 2
Sub FindReplace()
Dim wordApp As Object
Dim wordDoc As Object
Dim myStoryRange As Object
'~~> Sets up the word app
Set wordApp = CreateObject("Word.Application")
wordApp.Visible = True
'~~> Opens the document that we need to search through
Set wordDoc = wordApp.Documents.Open("C:\Users\routs\Desktop\Sample.docx")
For Each myStoryRange In wordDoc.StoryRanges
With myStoryRange.Find
.Text = "InsuranceCompanyName"
.Replacement.Text = "Fake Ins Co"
.Execute Replace:=wdReplaceAll
End With
Next myStoryRange
End Sub
在行动
推荐阅读
- java - MyBatis:使用注解选择复杂对象
- php - 使用 PDO 准备语句和遍历接口时如何指定 fetch_style?
- c# - 在 Visual Studio 中调试远程 dll 库
- javascript - Discord bot 显示离线,bot.js 中的 ReferenceError
- c++ - constexpr exp、log、pow
- java - 如何在spring项目中为多个环境动态配置数据源
- python - python列表中N个最大值的位置?
- c# - WPF 从 SystemParameter 单位转换为与设备无关的单位
- c# - 使用 Azure 存储异步创建 blob 时出现异常 - UploadTextAsync
- sql - SELECT子句SQL中出现多个字段时无法对单个字段进行GROUP BY