首页 > 解决方案 > 使用 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 部分要写什么。

标签: excelvbams-word

解决方案


问题是您的语法错误。.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

由于您使用的是后期绑定,因此您必须在使用之前为WdFindWrapWdReplace枚举定义 Word 常量

Const wdReplaceAll As Long = 2
Const wdFindContinue As Long = 1

或用它们的值替换它们

.Execute Replace:=2, Forward:=True, Wrap:=1

或设置对 Word 的引用并使用预绑定,以便自动定义它们。


推荐阅读