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

标签 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,我想不出解决方法。

最佳答案

这是我发现的解决问题的方法。这不是最有效的方法,而且如果表格中包含合并的单元格,它就不起作用。我发现您可以选择起始单元格的范围,然后通过以单元格为单位移动来扩展范围的终点。通过发现您要选择的区域的起点和终点之间的单元格数量,您可以迭代这些单元格步骤。下面是通用代码:

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

关于c# - 如何在 Word 表格中选择矩形单元格区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9026994/

相关文章:

c# - 如何在 Unity3D 中将特定音频源静音?

c# - 关键字 'event' 在 C# 中是可选的吗?

c# - 如何在 Selenium Webdriver 中处理 shadow dom

c# - 网页浏览器不刷新样式表

C# 将 Excel 图表作为对象(而不是图片)导出到 Word

c# - MS Word 自动化 : can't enable red underlines for spelling check

regex - Word 2013 中的通配符可匹配零个或多个空格

c# - Intellisense 无法从扩展方法推断类型

javascript - 如何通过WebDav打开包含某些字符的文档?

delphi - 如何使用 Delphi MSWord 自动化对齐段落?