Tuesday, June 26, 2007

Inserting text into a Word Document from VB.NET

Another post to the 'Office Series', I used to do this everyday in a previous job!! Al we did was automate word, but using templates, which was much cooler. For now this just adds text into a word document.


Private WordApp As New Word.ApplicationClass()

Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click

' Choose a word document
If Me.OpenFileDialog2.ShowDialog() = DialogResult.OK Then
' Get the file name from the open file dialog
Dim fileName As Object = OpenFileDialog2.FileName
' Make word visible, so you can see what's happening
WordApp.Visible = True
' Open the document
Dim aDoc As Word.Document = WordApp.Documents.Open(fileName)
' Add the text and a line break
WordApp.Selection.TypeText("VB.NET Rocks")
WordApp.Selection.TypeParagraph()
End If
End Sub

No comments: