2012-01-26 136 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))。

相關問題