Log in

View Full Version : VBA Word Table at Document Top



tcoombes
09-22-2011, 09:20 PM
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.

Frosty
09-23-2011, 09:35 AM
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.

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
However, if you're using the selection object, .SplitTable also works (although only on the selection object)

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

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.

tcoombes
09-23-2011, 11:31 AM
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.