簡體   English   中英

使用 VBA 從 Excel 中打開 Word Doc 以查找日期文本並將其替換為 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

由於您使用后期綁定,您必須在使用它們之前為WdFindWrapWdReplace枚舉定義 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM