You are hereInconsistencies in Microsoft Word API

Inconsistencies in Microsoft Word API

By Mel - Posted on 10 October 2009

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:

  1. Selection.Shading.ForegroundPatternColor = vbRed

Using the Range Object:

  1. Dim myrange As Range
  2. Set myrange = Selection.Range
  3. 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:

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

Using the Range Object:

  1. Dim myrange As Range
  2. Set myrange = Selection.Range
  3. For i = 1 To myrange.Cells.Count
  4. myrange.Cells(i).Shading.BackgroundPatternColor = wdColorViolet
  5. 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:

It took me hours to figure this out. I thought my code was the problem. It was Microsoft after all.

Post new comment

The content of this field is kept private and will not be shown publicly.
Enter the characters shown in the image.