Word 2010 VBA loop until next table not found. RRS feed

  • Question

  • Hi

    I'm trying to write a loop that copies information found in every second table into the first table on the page.  The code works but I haven't worked out how to stop it on the last page of the document.  I'd be grateful for any help or advice.

    Selection.HomeKey Unit:=wdStory

    Do Until ??

    'positions cursor at end of address
    'enters our ref and pipe

        Selection.MoveRight Unit:=wdCell
        Selection.MoveLeft Unit:=wdCell
        Selection.MoveRight Unit:=wdCharacter, Count:=1
        Selection.TypeText Text:="Our ref:  |"

    'moves to next table containing reference

        Application.Browser.Target = wdBrowseTable
        Selection.MoveDown Unit:=wdLine, Count:=1

    'copies ref

        Selection.EndKey Unit:=wdLine, Extend:=wdExtend
        Selection.MoveLeft Unit:=wdCharacter, Count:=1, Extend:=wdExtend
    'returns to first table and pastes in ref

        Selection.PasteAndFormat (wdFormatPlainText)
        Application.Browser.Target = wdBrowseTable

    'removes extra space in ref   
        With Selection.Find
            .Text = "| "
            .Replacement.Text = "|"
            .Forward = True
            .Wrap = wdFindContinue
            .Format = False
            .MatchCase = False
            .MatchWholeWord = False
            .MatchWildcards = False
            .MatchSoundsLike = False
            .MatchAllWordForms = False
        End With
        Selection.Find.Execute Replace:=wdReplaceAll
    End Sub

    Sunday, February 15, 2015 6:19 PM

All replies

  • When I do anything with tables in Word I use row and column addressing.  You can use something similar to this.

    Sub TableCopy()
        Set tbl1 = doc.Tables(1)
        Set tbl2 = doc.Tables(2)
        For r = 1 To tbl2.Rows.Count
          For c = 1 To tbl2.Columns.Count
            r1 = tbl1.Rows.Count
            Selection.InsertRowsBelow 1
            tbl1.Cell(r1 + 1, c).Range.Text = tbl2.Cell(r, c).Range.Text
          Next c
        Next r
    End Sub

    Sunday, February 15, 2015 7:11 PM
  • The doc.Tables.Count property gives you the number of tables in the doc so do a for each loop with a counter.

    Rod Gill
    Author of the one and only Project VBA Book

    Sunday, February 15, 2015 8:11 PM
  • Thanks Rod - I used that and it works great!
    Monday, February 16, 2015 10:04 AM
  • Thanks for your input mogulman52.  I've used Rod's method as it worked with my existing code.  Cheers.
    Monday, February 16, 2015 10:05 AM