Sunday, November 30, 2008

Automating Word with Ruby: Adding Bookmarks

Someone recently asked a question about using Ruby to add bookmarks to a Microsoft Word document. Here's a brief, but hopefully helpful, explanation...

Word's Document object includes a Bookmarks collection. To get a reference to this collection, call the Bookmarks() method on the Document object:

require 'win32ole'
word = WIN32OLE.connect('Word.Application')
doc = word.ActiveDocument
bookmarks = doc.Bookmarks()

To create a new bookmark, call the Add() method on the Bookmarks collection, passing it (1) a one-word name for the new bookmark, and (2) the range to be bookmarked. The following line of code adds a new bookmark, cleverly named 'Bookmark1', for the currently selected text:

bookmarks.Add('Bookmark1', word.Selection)

The Bookmarks collection includes (among others) a Count() method for getting the number of items in the collection, and an Exists() method for determining if a bookmark with that name already exists. So the following code prints the number of bookmarks, then adds a bookmark if it doesn't already exist, then prints the number of bookmarks again:

if not doc.Bookmarks.Exists('Bookmark1')
doc.Bookmarks.Add('Bookmark1', word.Selection)

To get a reference to an individual Bookmark, call the Bookmarks() method and pass it the name of the bookmark:

bookmark1 = doc.Bookmarks('Bookmark1')

To delete an individual Bookmark, call its Delete() method:


There you have it. Let me know if you have questions or comments. And, of course, there'll be more on this topic (and many others) in the book I'm currently working on.

Thanks for stopping by!


Antonio B Duarte Jr said...

I really aprecciate to read your blog. We here from Brazil have learned a lot from your posts. When is possible take a look mine Curso de Informática à Distância. Antonio B Duarte Jr.

Anonymous said...
This comment has been removed by a blog administrator.
Anonymous said...

I love Ruby, but with Win32OLE it is becoming profitable (darn, I thought I could keep it clean and innocent).

Could there be a little more "general" OLE-topics, like e.g. Dialogs, MessageBoxes, stuff you do to your Windows, rather than to Office?

That would be so nice. ;-)
TY a lot for all your work, so far!

Anonymous said...

Same Anonymous as the previous one.

For a nice integration of any small script into your Office-application, have a look at Shoes:

Immaculate dialogs are so easy to create, that I cannot but have to point you there...

In the meantime, all my Ruby/OLE-scripts have been extended with a Shoes-dialog and are integrated in the tool-bar of the program, they work with.