Shark Shark - 1 month ago 17
C# Question

How do you select a rectangular region of cells in a Word Table

Given something like

Table table;
Cell cell_1 = table.Cell(2,2);
Cell cell_2 = table.Cell(4,4);

I want to select (or highlight) from cell_1 to cell_2 (like how you would if you were doing it by hand).

I originally thought that doing the following would work:

Selection.MoveRight(wdUnits.wdCell, numCells, WdMovementType.wdExtend)

But according to under remarks, using wdCells as the Unit will default the WdMovementType to wdMove, and I can't think of a workaround.


Here is a workaround I've found to the problem. It isn't the most efficient way, and it doesn't work if the table has merged cells in it. I've discovered that you can select the range of your start cell, and then expand the end point of the range by moving by in units of cells. By discovering the number of cells between the start and end point of the region you want selected, you can iterate those number of cell steps. Here's the general code for that below:

word.Table table;
word.Cell cellTopLeft; //some cell on table.
word.Cell cellBottomRight; //another cell on table. MUST BE BELOW AND/OR TO THE RIGHT OF cellTopLeft

int cellTopLeftPosition = (cellTopLeft.RowIndex - 1) * table.Columns.Count + cellTopLeft.ColumnIndex;
int cellBottomRightPosition = (cellBottomRight.RowIndex - 1) * table.Columns.Count + cellBottomRight.ColumnIndex;
int stepsToTake = cellBottomRightPosition - cellTopLeftPosition;

if (stepsToTake > 0 && 
    cellTopLeft.RowIndex <= cellBottomRight.RowIndex && //enforces bottom right cell is actually below of top left cell
    cellTopLeft.ColumnIndex <= cellBottomRight.ColumnIndex) //enforces bottom right cell is actually to the right of top left cell
   word.Range range = cellTopLeft.Range;
   range.MoveEnd(word.WdUnits.wdCell, stepsToTake);