Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Word - calculating the number number of lines in a range using VBA 4

Status
Not open for further replies.

mdav2

Programmer
Aug 22, 2000
363
GB
I want to find the number of lines a selection is taking up in the document and then use this as a basis for some formatting.

I can find the number of characters but not the lines in a selection. Because I am using a proportion font characters are no good to me.

The tools, word count option returns the value but I need VBA to do it.

Anyone any ideas?
 
I am not sure why you need to know the number of lines. If you are formatting the selection, on what basis is the numbger of lines relevant? The number would change depending on the font size, page margin size, etc.

That being said, the only way I can think of is to create a new doc with the selection and do a line count of that. For what it is worth, here you go. A message box tells you how many lines. You can use the variable for whatever your are doing.

Sub SelectionLineCount()
'
Dim mDoc As Document, tempDoc As Document
Dim i As Integer

Application.ScreenUpdating = False
Set mDoc = ActiveDocument
If Selection.Type <> wdSelectionIP Then
Selection.Copy
Documents.Add DocumentType:=wdNewBlankDocument
Set tempDoc = ActiveDocument
Selection.PasteSpecial

i = tempDoc.BuiltInDocumentProperties(wdPropertyLines)
mDoc.Activate
tempDoc.Close (wdDoNotSaveChanges)
Application.ScreenUpdating = True
MsgBox "selection has " & i & " lines."
Set mDoc = Nothing
Else
MsgBox "Nothing selected.", vbCritical
End If
Application.ScreenUpdating = True
End Sub


Gerry
Painting/Sculpture site:
 
Hi mdav,

This should do it ..

Code:
[blue]Selection.Range.ComputeStatistics(wdStatisticLines)[/blue]

Enjoy,
Tony

------------------------------------------------------------------------------------------------------
We want to help you; help us to do it by reading FAQ222-2244 before you ask a question.
 
Uh, thanks Tony..quite a bit shorter than my code. Had not found that one. Learn something here all the time.

Of course it would need some error trapping, but hey, cool.

Gerry
Painting/Sculpture site:
 
Cheers guys, I have been scratching my head for ages trying to sort this one out. I think I need to find a really good reference book.
 
thank you both as well, this post was valuable to me too.

LikeThisName <- ? Sorry It's Taken =)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top