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?
Just use Selection.Range object instead of ActiveDocument
Sub Count_Lines()
MsgBox ("The selection contains " & Selection.Range.ComputeStatistics(wdStatisticLines) & " Lines")
End Sub
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With