timbmg
timbmg

Reputation: 3328

Read currently selected line

(this should propably be simple, but somehow i cannot find a solution.)

I simply want to read the current line of my selection into a variable in vba. I do not know the current paragraph. The selection is at the very beginning of the line.

My document looks like this.

My Word doc

First of all I select the first row of the table. Then i move one paragraph up. Now thats the line I want. As you can see in my second img, I only have the first character.

For Each tbl In fileInsertRange.Tables
    tbl.Rows(1).Select
    ' save caption
    Selection.Collapse
    Selection.MoveUp WdUnits.wdParagraph, 1

    tableCaption = Selection.Text

Debugging

Upvotes: 0

Views: 90

Answers (1)

Hubvill
Hubvill

Reputation: 504

If you want to store all your tables captions in a variable than try this code. Keep in mind you'd need to use the tableCaption variable right away before it gets overwritten by the next tables caption or add an array to store all of the captions.

Sub get_table_caption()

Dim currentTable As Table
Dim tableCaption As String

'Loop through all tables on active document
For Each currentTable In ActiveDocument.Tables

    'Get tables caption and store in a variable called "tableCaption"
    currentTable.Select
    Selection.Collapse
    Selection.MoveUp WdUnits.wdParagraph, 1
    Selection.Expand wdLine
    tableCaption = Selection.Text
    Debug.Print tableCaption

    'Do stuff with the tables caption

Next
End Sub

If you want to continue doing it your way by selecting the first row of the table and finding that tables caption than try this code:

Sub get_table_caption()

Dim tableCaption As String

    'Get tables caption and store in a variable called "tableCaption"
    Selection.Collapse
    Selection.MoveUp WdUnits.wdParagraph, 1
    Selection.Expand wdLine
    tableCaption = Selection.Text
    Debug.Print tableCaption

End Sub

Hope that helps. Good luck.

Upvotes: 1

Related Questions