我正在使用带有预定义字段(书签)的word文档模板!该书签在运行时由实际值有问题更新,并且工作正常,但文档中的某些单词未标记为书签,因此我使用了Find&替换Microsoft.Office.Interop.Word
的特征以用实际值替换该单词,但是当它用包含换行符的文本替换单词时,换行符不会出现在文档中,整个文本以单行显示。
在下面的代码中,我已经替换了文本"地址"在包含以下文字的文件中
Park Royal House No: 3301 Wing - D
City: xxxx
State: YY
Zip: 100215
但它出现在像这样的文件中
Park Royal House No: 3301 Wing - D City: xxxx State: YY Zip: 100215
按照示例代码替换word doc
中的文本Private Sub ReplaceWorkDocText()
Dim objApplication As Microsoft.Office.Interop.Word.ApplicationClass = Nothing
Dim objDocument As Microsoft.Office.Interop.Word.Document = Nothing
Dim findText As String = "Address"
Dim replaceText As String = "Park Royal House No: 3301 Wing - D" + _
vbCrLf + "City: xxxx" + _
vbCrLf + "State: YY" + _
vbCrLf + "Zip: 100215"
objApplication = New Microsoft.Office.Interop.Word.ApplicationClass()
objDocument = objApplication.Documents.Open("C:\TEST\FORM0001.docx")
With objDocument.Range.Find
.Text = findText
.Replacement.Text = replaceText
.Forward = True
.Execute(Replace:=Microsoft.Office.Interop.Word.WdReplace.wdReplaceOne)
End With
End Sub
请帮我解决如何用换行符替换文档中的单词。
答案 0 :(得分:1)
我使用这个工作来做同样的事情,它的工作正常。
Private Sub ReplaceWorkDocText()
Dim objApplication As Microsoft.Office.Interop.Word.ApplicationClass = Nothing
Dim range As Microsoft.Office.Interop.Word.Range
Dim objDocument As Microsoft.Office.Interop.Word.Document = Nothing
Dim findText As String = "Address"
Dim replaceText As String = "Park Royal House No: 3301 Wing - D" + _
vbCrLf + "City: xxxx" + _
vbCrLf + "State: YY" + _
vbCrLf + "Zip: 100215"
objApplication = New Microsoft.Office.Interop.Word.ApplicationClass()
objDocument = objApplication.Documents.Open("C:\TEST\FORM0001.docx")
range= objDocument.Range
With range.Find
.Text = findText
.Forward = True
End With
While range.Find.Execute(findText, MatchWholeWord:=True)
range.Text = replaceText
Exit While
End While
End Sub