问题
I want to open an existing .docx file and insert some text in second paragraph.
Private Sub insertText()
Dim WordApp As New Microsoft.Office.Interop.Word.Application
Dim aDoc As Microsoft.Office.Interop.Word.Document = WordApp.Documents.Open("C:\File1.docx")
Dim RNG As Microsoft.Office.Interop.Word.Range()
end sub
Now what should I write to insert some text in second para ?? Any help will be greatly appreciated. Thanks in advance.
回答1:
You can use Application.Selection.TypeText()
for that:
Private Sub insertText()
Dim WordApp As New Microsoft.Office.Interop.Word.Application
WordApp.Visible = True
Dim aDoc As Microsoft.Office.Interop.Word.Document = WordApp.Documents.Open("C:\File1.docx")
Dim paragraphs As Word.Paragraphs = aDoc.Paragraphs
If (paragraphs.Count > 1) Then
paragraphs(2).Range.Select()
WordApp.Selection.TypeText("test")
End If
aDoc.Save()
aDoc.Close()
WordApp.Quit()
End Sub
You should probably close up the document then word safely so you don't have a winword.exe hanging after your program is finished ( I added this quick-and-dirty for you, but its not 100% foolproof)
Please excuse my poor, lazy vb.net style. If you like c sharp - note that c sharp since v4.0 is MUCH better than it used to be with Office Interop, and I recommend it.
回答2:
Yes.. I got the answer..
Private Sub insertText()
Dim WordApp As New Microsoft.Office.Interop.Word.Application
Dim aDoc As Microsoft.Office.Interop.Word.Document = WordApp.Documents.Open("C:\File1.docx")
Dim RNG As Microsoft.Office.Interop.Word.Range()
Dim PARA As Microsoft.Office.Interop.Word.Paragraph = aDoc.Paragraphs.Add()
If aDoc.Paragraphs.Count > 1 Then
aDoc.Paragraphs(2).Range.InsertParagraphBefore()
aDoc.Paragraphs(2).Range.Text = "Hello World"
end if
end sub
This code first a new para above second para and inserts Hello World in newly created second para. Cheers....
来源:https://stackoverflow.com/questions/21139450/how-to-add-a-text-in-existing-docx-file-on-desired-location