Automating Microsoft Word from Visual Basic

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.

Imports Microsoft.Office.Interop.Word

 

Module Module1

Sub Main()

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

range.Collapse(WdCollapseDirection.wdCollapseEnd)

doc.Bookmarks.Add(“MijnBookmark”, range)

 

‘ 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

End Sub

End Module

 

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.

Enjoy!

5 thoughts on “Automating Microsoft Word from Visual Basic

  1. How to Goto any location or bookmark; get point of cursor; replace text… in the open file.doc?
    Please code more
    Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>