'How to get Line Count in MS Word?
I am using Word Interop to calculate the number of lines present in a Table Cell.
The Cell in question is shown below (Special characters enabled for clarity).
The number of new line characters present in the text are 3. However, due to the length of the second text it is extended into a second line resulting in 4 lines.
The following code which calculates the number of new line characters returns 3.
input.Count(x => x == '\r'); //Result:3
The Word Count tool provided by Word provides the correct result, 4 lines.
The following code uses the Cell.Range property to access the ComputeStatistics function which the Word Count tool uses. However the result of the function call is always 0.
lines = cell.Range.ComputeStatistics(WdStatistic.wdStatisticLines); //Result:0
I tried iterating over all Paragraphs within the Range, calling the ComputeStatistics function for each Paragraph.Range separately while calculating a running total. The first paragraph returns a value of 1 but all subsequent calls return the value 0.
How do I get the value of line count shown by the Word Count tool?
What, if any, alternatives exist to get an accurate Line Count in Word?
Solution 1:[1]
Something about the end-of-cell marker seems to interfere with the statistics. This worked for me in VBA though:
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
Solution 2:[2]
Here is the implementation code in 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;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Tim Williams |
Solution 2 | demoncrate |