2012-01-26 138 views
2

从cell_1鉴于类似如何在Word表格选择单元格的矩形区域

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

我要选择(或高亮)到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,我不能想到一个解决办法的。

回答

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

一个更简单的方式做到这一点是使用Document.Range方法来创建矩形的两个角之间的范围。这与合并的单元格同样适用。

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

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

注:人们可以使用由该表达式返回到操作表中的内容不选择它的范围内,但它不用于合并细胞起作用(在后一种情况下,使用cell.Merge(MergeTo))。

相关问题