Automating Microsoft Word from Visual Basic

Posted Monday, December 10, 2007 11:42 AM by Maurice

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 Smile

 

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!

Filed under: , , ,

Comments

# re: Automating Microsoft Word from Visual Basic

Thursday, December 13, 2007 10:44 PM by danilo ravanilla jr

how to find my cd key?

# re: Automating Microsoft Word from Visual Basic

Monday, January 14, 2008 10:51 AM by Do Thai Hoa

How to Goto any location or bookmark; get point of cursor; replace text...  in the open file.doc?

Please code more

Thanks.

# re: Automating Microsoft Word from Visual Basic

Monday, January 14, 2008 10:51 AM by Do Thai Hoa

How to Goto any location or bookmark; get point of cursor; replace text...  in the open file.doc?

Please code more

Thanks.

# re: Automating Microsoft Word from Visual Basic

Tuesday, January 15, 2008 1:56 AM by Maurice

If you want to move the user to a specific point in the doc you need to set the Selection.

Leave a Comment

(required) 
(required) 
(optional)
(required)