0
votes

Whenever I update the document, I need to add a row to the top of the table, just below the headers, and then move the old row to the next level. The table is usually present on the last page of the Word document. Please find attached the screenshot for the expected and actual behaviors. Below is the code I have written to achieve:

  1. Go to the last page and find the table
  2. Add a row (This adds above the column header)

Expectations:

  1. Add the row immediately after the column header and move the existing row to the next level
  2. Add the date to the second column. Click for the screenshot

My code:

Sub Macro1()

Selection.EndKey Unit:=wdStory
Dim theTable As Table
Dim theNewRow As Row
For Each theTable In ActiveDocument.Tables
    Set theNewRow = theTable.Rows.Add(theTable.Rows.First)
    'Other row formatting
Next theTable

End Sub

I am learning VBA and any help would be of great use. Thanks for your time.

screenshot2

3

3 Answers

0
votes

For example:

With ActiveDocument
  With .Tables(.Tables.Count)
    .Split (2)
    With .Range.Characters.Last.Next
      .FormattedText = .Next.Rows(1).Range.FormattedText
    End With
    .Rows(2).Range.Delete
  End With
End With

It's not clear, though, what you mean by "move the existing row to the next level".

0
votes

It needs next.

Sub test()
    Selection.EndKey Unit:=wdStory
    Dim theTable As Table
    Dim theNewRow As Row
    For Each theTable In ActiveDocument.Tables
        Set theNewRow = theTable.Rows.Add(theTable.Rows.First.Next) '<~~ add next
    
        'Other row formatting
    Next theTable
End Sub
0
votes

As Intellisense shows you the input parameter for Table.Rows.Add is [BeforeRow]. This is an optional parameter so if it is omitted the new row is added after the last row of the table.

As you want the row to come after the first row and before the second you need to pass the second row as the parameter, e.g.

With ActiveDocument.Tables(ActiveDocument.Tables.Count)
   With .Rows.Add(.Rows(2))
      'add date
      .Cells(2).Range.Text = Format(Date, "MMMM d, yyyy")
      'add any additional row formatting
   End With
End With