excel - 使用 VBA 从 Excel 中打开 Word Doc 以查找日期文本并将其替换为 Excel 中单元格中的日期文本
问题描述
我有一个带有文本的 word doc,其中还有一个显示这种格式的日期文本:
text text text 17.01.2020 text text text.
我想用 Excel 中的一个单元格替换上述日期文本,该单元格也是一个类似于 18.01.2020 的日期。
因此 VBA 代码应该执行以下操作:
1.打开word文档
2.找到文本并将其替换为Excel中的文本
3.保存Word文档。
Sub DocSearchandReplace()
Dim wdApp As Object, wdDoc As Object
Set wdApp = CreateObject("word.application")
wdApp.Visible = True
Set wdDoc = wdApp.Documents.Open("C:\sampletest.docx")
With wdDoc.Content.Find
.Date = "???"
.Replacement.Cell = "referencing a cell from Excel??"
.Wrap = wdFindContinue
.Execute Replace:=wdReplaceAll
End With
wdDoc.Save 'it however always prompt a word warning, how to surpress it?
wdDoc.Close 'it only closes the doc inside Word without closing the whole program.
Set wdApp = Nothing: Set wdDoc = Nothing
End Sub
我不确定在 .Date 和 .Replacement.Cell 部分要写什么。
解决方案
问题是您的语法错误。.Date
并且对象.Replacement.Cell
中不存在Find
属性。确保阅读查找对象的手册并且不要发明属性。
根据 查找和替换文本或格式的正确语法类似于:
With wdDoc.Content.Find
.ClearFormatting
.Text = "17.01.2020" 'your date to replace
.Replacement.ClearFormatting
.Replacement.Text = ThisWorkbook.Worksheets("Sheet1").Range("A1").Text 'read value from sheet1 cell A1
.Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindContinue
End With
根据 Cindys 的评论,Word 中存在通配符匹配,类似于使用正则表达式。
With wdDoc.Content.Find
.ClearFormatting
.Text = "[0-9]{2}.[0-9]{2}.[0-9]{4}" 'will match ##.##.####
.MatchWildcards = True 'makes sure the above wildcards are recognized
.Replacement.ClearFormatting
.Replacement.Text = ThisWorkbook.Worksheets("Sheet1").Range("A1").Text 'read value from sheet1 cell A1
.Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindContinue
End With
由于您使用的是后期绑定,因此您必须在使用之前为WdFindWrap和WdReplace枚举定义 Word 常量
Const wdReplaceAll As Long = 2
Const wdFindContinue As Long = 1
或用它们的值替换它们
.Execute Replace:=2, Forward:=True, Wrap:=1
或设置对 Word 的引用并使用预绑定,以便自动定义它们。
推荐阅读
- c - 图的边
- mysql - 查询获取上周添加的产品详情
- angular - 在响应时删除 Angular Material 分页
- jquery - 如果鼠标快速移动,则 Jquery 悬停问题
- python - 如何从全局类范围访问 self.function
- android - DialogFragment.dismiss() leaves keyboard on screen
- java - 如何在自定义 getter 中序列化 JSON 对象?
- javascript - Mobile click on body does not fire
- sas - ODBC 和 Netezza 引擎之间的区别
- r - position_dodge on geom_text on dodged barplot