Properly Manipulating the Selection in a Word Document

Filed under Uncategorized

The Word object model is an unbelievable rich hierarchy of objects devoted to letting you navigate just about every facet of a particularly complex chunk of data, namely a WYSIWYG document.

Still, there are right ways to use it and wrong. And when you do things wrong with Word, it usually doesn’t just erupt in a massive fireball. Instead, often, something seemingly completely unrelated will fail much farther on down the line, making for some thoroughly enjoyable debugging sessions.</sarcasm>

For instance. I’d been working on a Word Addin that processes the contents of a Word document. It does a pretty thorough job, so it basically hits just about every nook and cranny in the object model.

One technique I’d had to use involved selecting a field, and then pasting text over it, effectively replacing the field with plain text.

The code looked something like this:



Application.Selection.PasteSpecial link:=False, DataType:=wdPasteMetafilePicture, Placement:=wdFloatOverText, DisplayAsIcon:=False

Basically, it SELECTed the field, then copied the selection, effectively converting the field to plain text.

And finally, it PASTEd the text back over the selection, wiping out the field with just the plain text content.

It may not be the ideal way to handle this, but other methods failed outright for a variety of reasons, and this technique worked quite nicely and consistently.

That is, until I added code (in a completely unrelated portion of the application), to enumerate all the bookmarks in the document and retrieve information on them.

When I did so, another loaded document  (i.e. not the current document I was working with) would have the contents of the clipboard pasted into its main body.

Needless to say, chasing down these two essentially unrelated pieces of code was no small chore.

But once I knew what was causing the problem, I needed to determine how to fix it.

The main problem was that the Word Document object doesn’t have a Selection property. Only the Application object does, which was global to all loaded documents, and was quite likely the source of the cross contamination.

However, a little digging turned up that the Document object contains an ActiveWindow property returning a Window object.

And the Window object does have a Selection property.

Changing the code to this solved the problem:



CurDoc.ActiveWindow.Selection.PasteSpecial link:=False, DataType:=wdPasteMetafilePicture, Placement:=wdFloatOverText, DisplayAsIcon:=False

The CurDoc object is the Document object I’m currently working with.

Essentially, instead of using the selection property of the Application object, I’m using the more specific one on the actual document I’m currently working on.

Under normal circumstances, the two approaches are identical, but, at least in this case, they aren’t.

Post a Comment

Your email is never published nor shared. Required fields are marked *