Using COM to automate Word from your Visual Basic application isn’t very hard. Just did a sample for a friend and decided to share it. Not that the sample is very complicated or anything, quite the opposite in fact. But it does show how easy it is to get started [:)]
The sample code below shows how to construct a minimal document, insert a bookmark and, at a later moment, replace the empty bookmark with some text.
Dim word As New Application
word.Visible = True
Dim doc As Document = word.Documents.Add()
Dim range As Range = doc.Range
‘ Insert some text
range.InsertAfter(“Range1″ + vbCrLf)
‘ Insert a bookmark, make sure the range is 0 characters long so we can insert text
‘ Add some more text
range.InsertAfter(“Range2″ + vbCrLf)
‘ Get a reference to the bookmark
Dim bookmark As Bookmark = doc.Bookmarks(1)
range = bookmark.Range
‘ Insert the text
range.Text = “Bookmark” + vbCrLf
‘ Change the font for the bookmark
range.Font.Color = WdColor.wdColorRed
range.Font.Italic = 1
One thing to keep in mind when automating Word is that, in general, it is better to use Range objects instead of the Selection. One reason is that there is only one selection while you can have multiple ranges but there is also a performance penalty to using the selection. And don’t forget to install the Office PIA’s when using Office through COM from .NET.
Another useful thing is the Word Macro Recorder. It is still there in Word 2007 but hidden away in the Developer Ribbon bar. Kind of strange as the macro recorder was always the simplest way of automating Word for the average user and they typically don’t have the developer ribbon visible.