How can you get the current table in MS Word VBA?

I realise this is a rather old question, but I stumbled across some code that may help the next person who is facing a similar problem.

ActiveDocument.Range(0, Selection.Tables(1).Range.End).Tables.count

This will return the index of the table the cursor is in. Which can then be used to make changes or retrieve information:

dim numberOfColumnsInCurrentTable as Integer
dim currentTableIndex as Integer

currentTableIndex = ActiveDocument.Range(0, Selection.Tables(1).Range.End).Tables.count
numberOfColumns = ActiveDocument.Tables(currentTableIndex).Columns.count

Obviously checks should be added to ensure the cursor is within a table.


The VBA subroutine at the bottom of this answer shows how to do this.

It uses the current selection, collapsing it to the starting point first so as to not have to worry about multi-segment selections:

Selection.Collapse Direction:=wdCollapseStart

It then checks that selection to ensure it's inside a table

    If Not Selection.Information(wdWithInTable) Then
        MsgBox "Can only run this within a table"
        Exit Sub
    End If

The table is then accessible by referring to Selection.Tables(1).


The code below was a simple proof of concept which simply toggled each of the starting cells in each row of the table to either insert or delete a vertical bar marker.

Sub VertBar()
    ' Collapse the range to start so as to not have to deal with '
    ' multi-segment ranges. Then check to make sure cursor is '
    ' within a table. '
    Selection.Collapse Direction:=wdCollapseStart
    If Not Selection.Information(wdWithInTable) Then
        MsgBox "Can only run this within a table"
        Exit Sub
    End If

    ' Process every row in the current table. '
    Dim row As Integer
    Dim rng As Range

    For row = 1 To Selection.Tables(1).Rows.Count
        ' Get the range for the leftmost cell. '
        Set rng = Selection.Tables(1).Rows(row).Cells(1).Range

        ' For each, toggle text in leftmost cell. '
        If Left(rng.Text, 2) = "| " Then
            ' Change range to first two characters and delete them. '
            rng.Collapse Direction:=wdCollapseStart
            rng.MoveEnd Unit:=wdCharacter, Count:=2
            rng.Delete
        Else
            ' Just insert the vertical bar. '
            rng.InsertBefore ("| ")
        End If
    Next
End Sub

Tags:

Ms Word

Vba