如何在 MS Word 中获取行数?

How to get Line Count in MS Word?

我正在使用 Word Interop 来计算 Table Cell.
中存在的行数 有问题的单元格如下所示(为清楚起见,启用了特殊字符)。

文本中出现的换行符数为 3。但是,由于第二个文本的长度,它被扩展到第二行,导致 4 行。

下面的代码计算换行符的个数returns 3.

input.Count(x => x == '\r'); //Result:3

Word提供的字数统计工具给出了正确的结果,4行。

以下代码使用 Cell.Range 属性 访问字数统计工具使用的 ComputeStatistics 函数。然而,函数调用的结果始终为 0。

lines = cell.Range.ComputeStatistics(WdStatistic.wdStatisticLines); //Result:0

我尝试遍历范围内的所有段落,分别为每个 Paragraph.Range 调用 ComputeStatistics 函数,同时计算 运行 总数。第一段 return 的值为 1,但所有后续调用 return 的值为 0。

如何获取字数统计工具显示的行数值?
如果有的话,有什么替代方法可以在 Word 中获得准确的行数?

有关单元格结束标记的某些内容似乎干扰了统计数据。不过,这在 VBA 对我有用:

Dim c As Cell, rng As Range

Set c = ThisDocument.Tables(1).Cell(1, 1)
Set rng = c.Range
rng.MoveEnd wdCharacter, -1

Debug.Print rng.ComputeStatistics(wdStatisticLines)  '4

这里是C#中的实现代码

private int GetNumberOfLinesInRange(Cell cell)
{
     int lines = -1;
     Range cellRange = cell.Range;

     //Range decreased by 1 
     //to omit the end of cell marker from the calculation which 
     //interferes with the ComputeStatistics result
     cellRange.MoveEnd(WdUnits.wdCharacter, -1); 

     lines = cellRange.ComputeStatistics(WdStatistic.wdStatisticLines);
     return lines;
}