Consulting

Results 1 to 3 of 3

Thread: VBA Word Table at Document Top

  1. #1
    VBAX Regular
    Joined
    Sep 2011
    Posts
    10
    Location

    Exclamation VBA Word Table at Document Top

    I am automating Word from Access and have Opened an existing document and want to add a new table the top.

    Set MyWordDoc = MyWordApp.Documents.Open(InFileName)

    I select the range at the very top of my doc

    Set MyRange = MyWordDoc.Range(Start:=0, End:=0)

    If this is a blank line or a paragraph in word then I can add a table

    Set MyWrdTbl = MyWordDoc.Tables.Add(MyRange, 4, 3)

    However if the Very top of my original word document was itself a table and there was nothing above that in the document my statement

    Set MyRange = MyWordDoc.Range(Start:=0, End:=0) has selected the cell of the original table that was at the top of the document.

    I then end up with my new table being a table within a table as it gets inserted within that cell


    Normally if you actually open a word doc and find the cursor lies within the first cell of a table you can use the enter key and it will shift the table down and give you a working line outside and above that table.

    I thought I might be able to do the same in VBA by using sendkeys and{enter} but that does nothing.

    Anyone know how to move that top table down so I can select a range above it for my new table.

  2. #2
    VBAX Master
    Joined
    Feb 2011
    Posts
    1,480
    Location
    Funny how old solutions get found. This made me curious as well... and apparently the problem has a few solutions (none of them ideal). This one from Macropod (from 2004!) seems the best of the lot.
    [vba]
    Sub DealingWithATable()
    If ActiveDocument.Range(0, 0).Information(wdWithInTable) Then
    With ActiveDocument.Tables(1)
    .Rows.Add .Rows(1)
    .Rows(1).Cells.Merge
    .Rows(1).ConvertToText
    End With
    End If
    ActiveDocument.Tables.Add ActiveDocument.Range(0, 0), 3, 4
    End Sub
    [/vba] However, if you're using the selection object, .SplitTable also works (although only on the selection object)
    [vba]
    Sub DealingWithATableUsingSelection()
    If ActiveDocument.Range(0, 0).Information(wdWithInTable) Then
    ActiveDocument.Range(0, 0).Select
    Selection.SplitTable
    End If
    ActiveDocument.Tables.Add ActiveDocument.Range(0, 0), 3, 4
    End Sub
    [/vba]
    There is also a method of cutting the table, inserting a paragraph, and pasting it back in... but I'd choose one of the above 2, depending on your needs.

  3. #3
    VBAX Regular
    Joined
    Sep 2011
    Posts
    10
    Location

    Thumbs up

    Thanks for that. It does exactly what I want.

    I never thought of adding a blank row and then converting that row to text.

    Very smart whoever thought of that one.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •