Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count selected lines in MS Word

Tags:

ms-word

count

vba

I wanted to count the lines of selected text in MS word document. I come up with code:

Sub Count_Lines()
ActiveDocument.ComputeStatistics (wdStatisticLines)
MsgBox ("The document contains " & NumLines & " Lines")
End sub

But it actually count the line of whole document.

Can anybody help, finding code which could count selected line only?

like image 762
Ibn e Ashiq Avatar asked Nov 27 '25 01:11

Ibn e Ashiq


2 Answers

Just use Selection.Range object instead of ActiveDocument

Sub Count_Lines()
    MsgBox ("The selection contains " & Selection.Range.ComputeStatistics(wdStatisticLines) & " Lines")
End Sub
like image 52
SergeyLebedev Avatar answered Nov 29 '25 14:11

SergeyLebedev


Your code intends to show the value of NumLines in the message box. However, no value was assigned to that variable. In fact the variable itself was also not declared. The code below fills these two shortcomings and then works just fine. However, it will count all the lines in the document. If you just want the selected lines use the solution offered below.

Option Explicit

Sub Count_Lines()

    Dim NumLines As Long

    NumLines = ActiveDocument.ComputeStatistics(wdStatisticLines)
    MsgBox ("The document contains " & NumLines & " Lines")
End Sub

NB. They say, Option Explicit "forces" you to declare variables which forces the reaction to resist. Compare the force with that of the traffic police who insist on your driving on the right side of the road. Using Option Explicit will not prolong your life but it will drastically reduce the amount of time you spend chasing stupid errors because you are too proud to let your computer point them out to you. Option Explicit was the tool that provided me with an immediate pointer to the source of the problem you are seeking help on here.

like image 20
Variatus Avatar answered Nov 29 '25 15:11

Variatus