Word VBA - Selecting Tables

Posted on 2012-08-21
Last Modified: 2012-08-21
Hi Experts,

Does anyone know how I can select a table in a Word document based on the value of the first cell? I.e. Instead of using ActiveDocument.Tables(2).Select, I could replace the value of the direct reference to the table with the value of the first cell in the desired table, such as the title of the table which is a unique value.


Question by:MrDavidThorn
    LVL 76

    Accepted Solution

    Just step through  the tables and check the cell particular cell contents.

    Sub SelectTableByText()
        Dim tbl As Table
        Dim strText As String
        strText = "My Text"
        For Each tbl In ActiveDocument.Tables
            If GetCellText(tbl.Range.cells(1)) = strText Then
                Exit For 'to select first eligible table. else last such table will be selected
            End If
        Next tbl
    End Sub
    Function GetCellText(cl As Cell) As String
        Dim rng As Range
        Set rng = cl.Range
        rng.MoveEnd wdCharacter, -1
        GetCellText = rng.Text
    End Function

    Open in new window


    Author Comment

    Excellent - thank you

    Author Closing Comment

    Thank you

    Featured Post

    IT, Stop Being Called Into Every Meeting

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    Join & Write a Comment

    This is written from a 'VBA for MS Word' perspective, but I am sure it applies to most other MS Office components where VBA is used.  One thing that really bugs me is slow code, ESPECIALLY when it's mine!  In programming there are so many ways to…
    The System Center Operations Manager 2012, known as SCOM, is a part of the Microsoft system center product that provides the user with infrastructure monitoring and application performance monitoring. SCOM monitors:   Windows or UNIX/LinuxNetwo…
    This video shows and describes the main difference between both orientations in Microsoft Word. Viewers will understand when to use each orientation and how to get the most out of them.
    Learn how to make your own table of contents in Microsoft Word using paragraph styles and the automatic table of contents tool. We'll be using the paragraph styles in Word’s Home toolbar to help you create a table of contents. Type out your initial …

    732 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    19 Experts available now in Live!

    Get 1:1 Help Now