How to add a text in existing .docx file on desired location

元气小坏坏 提交于 2020-01-06 14:07:02

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!