如何在Word表中选择矩形单元格区域

时间:2012-01-26 23:25:53

标签: c# ms-word

给出类似

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

我想从cell_1到cell_2选择(或突出显示)(就像你手工做的那样)。

我原本以为做以下工作会有效:

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

但是根据http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.selection.moveright%28v=office.11%29.aspx的评论,使用wdCells作为单位会将WdMovementType默认为wdMove,我想不出解决方法。

2 个答案:

答案 0 :(得分:1)

这是我发现问题的解决方法。它不是最有效的方式,它doesn't work if the table has merged cells in it。我发现你可以选择起始单元格的范围,然后通过以单元格为单位移动来扩展范围的终点。通过发现所选区域的起点和终点之间的单元格数,可以迭代这些单元格步数。以下是以下的一般代码:

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);
   range.Select();      
}

答案 1 :(得分:1)

更简单的方法是使用Document.Range方法在矩形的两个角之间创建一个范围。这对合并的单元格同样有效。

word.Document document;    
word.Cell cellTopLeft;
word.Cell cellBottomRight;

document.Range(cellTopLeft.Range.Start, cellBottomRight.Range.End).Select

注意:可以使用此表达式返回的范围来操作表的内容而不选择它,但它不能用于合并单元格(在后一种情况下,使用cell.Merge(MergeTo))。 / p>