Sanghita
Sanghita

Reputation: 1317

vba macro: Which table my cursor is in?

Writing a macro I found out that I need to skip the table contents and place my cursor right after that, for this I am using a code as

     Selection.Tables(cnt).Select
     Selection.Collapse WdCollapseDirection.wdCollapseEnd

Here, cnt is a counter value which increases each time a table is found, but if run the macro in selective pages then how will i know the number of nth table inside which my cursor is.

Upvotes: 3

Views: 6184

Answers (2)

GSerg
GSerg

Reputation: 78185

The table in which your cursor is is always Selection.Tables(1).

If Selection.Tables.Count > 0 Then
  Dim r As Range
  Set r = Selection.Tables(1).Range
  r.Collapse wdCollapseEnd

  r.Select
End If

In case of nested tables, you might want to also check Selection.Tables.NestingLevel. The following will exit any number of nested tables, placing the cursor after the outermost table:

If Selection.Tables.Count > 0 Then
  Dim r As Range, i As Long

  Set r = Selection.Range

  For i = 1 To r.Tables.NestingLevel
    Set r = r.Tables(1).Range
    r.Collapse wdCollapseEnd
  Next

  r.Select
End If

Upvotes: 4

Kazimierz Jawor
Kazimierz Jawor

Reputation: 19067

Important! This solution allows you to find the number of currently selected table within document.

Add this function to any your Module:

Function WhichTableNo(RNG As Range)

If RNG.Tables.Count > 0 Then
    Dim DOC As Document
    Set DOC = RNG.Parent

    Dim rngTMP As Range
    Set rngTMP = DOC.Range(0, RNG.Tables(1).Range.End)

    WhichTableNo = rngTMP.Tables.Count
Else
    WhichTableNo = "Not in the table"
End If
End Function

and to check the table number you could call it this way:

debug.Print WhichTableNo(Selection.Range)

As a result you get number of table you are currently in.

Upvotes: 5

Related Questions