Loveb
Loveb

Reputation: 335

Whats the lenght of current line?

If you want to know the length of the whole paragraph, that's easy, you just type Len(Selection.Paragraphs(1).Range.Text), but this paragraph has a "shift enter" (a new line) in it. How do I get the length of current line? I want something like: Len(Selection.wdLines(1).Range.Text)

I found one work around, but it contains selecting the text and I don't want that. Please help.

Selection.HomeKey Unit:=wdLine
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
Debug.Print Len(Selection)

Upvotes: 0

Views: 59

Answers (1)

JohnM
JohnM

Reputation: 3350

This assumes the type of Selection is relevant (eg not a Shape), that the Selection is all within a single line, also no specific handling for Tables (calling code should check).

The returned number excludes the line-feed, carriage-return, tab character(s) at the start and end of the line.

Function GetSelectionLineLength() As Long
    Const sEND_AT As String = vbCr & vbLf & vbTab & vbVerticalTab & vbFormFeed
    Dim rng As Range
    Set rng = Selection.Range
    rng.MoveStartUntil sEND_AT, wdBackward
    If rng.Start > 0 Then
        If InStr(1, sEND_AT, rng.Previous.Text, vbBinaryCompare) = 0 Then
            ' the start of the Range didn't move as the line is right at the start of the Document
            rng.Start = 0
        End If
    End If
    rng.MoveEndUntil sEND_AT, wdForward
    GetSelectionLineLength = rng.End - rng.Start
End Function

Upvotes: 2

Related Questions