![](/img/trans.png)
[英]VBA to find specific text in word doc and copy this text from word doc into a cell in excel
[英]Open a Word Doc from Excel using VBA to find a Date text and replace it with a date text from a cell in Excel
我有一个带有文本的 word 文档,那里还有一个日期文本显示这种格式:
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 部分写什么。
问题是你的语法错误。 Find
对象中不存在.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 的引用并使用早期绑定,以便自动定义它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.