Search code examples
c#vbams-wordoffice-interop

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).
enter image description here

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.
enter image description here

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

  • 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
    

    enter image description here