I am using Word Interop to calculate the number of lines present in a Table
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 actual lines.
The following code which simply calculates the number of new line characters does not work as it 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 have 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 reliably get an accurate Line Count in Word?
CodePudding user response:
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