MisterAtMisis.com

Inconsistencies in Microsoft Word API

Sat Oct 10 2009 - Mel

I was trying to create a new function for our system using Visual Studio Tools for Office (VSTO). The new function was supposed to manipulate the selected cells of a table in a Microsoft Word 2007 document. As I test the function, I came across an inconsistency in the behavior of the Range Object of a Selection.

The Range of a selection behaves similarly with the Selection object itself. For example, the following sets of code both change the background color of the selected cells to red.

Using the Selection Object:

Selection.Shading.ForegroundPatternColor = vbRed

Using the Range Object:

Dim myrange As Range Set myrange = Selection.Range myrange.Shading.BackgroundPatternColor = vbRed

So if you create the following table and select the two cells containing 'b' and 'e', you would get the following results for both sets of code.

However, the Cells collection of the Range object behaves differently with that of the Selection object in that it includes cells that are not selected.

Using the Selection Object:

For i = 1 To Selection.Cells.Count Selection.Cells(i).Shading.BackgroundPatternColor = wdColorViolet Next

Using the Range Object:

Dim myrange As Range Set myrange = Selection.Range For i = 1 To myrange.Cells.Count myrange.Cells(i).Shading.BackgroundPatternColor = wdColorViolet Next

As most developers familiar with the MS Office API know, using a Range object is more convenient in many situations but this time it is better to use the Selection object.

For more on the difference between Selection and Range object, visit the ff. link:

http://msdn.microsoft.com/en-us/library/aa164764(office.10).aspx