如何用Word VBA在表头下方新增行并下移原有行?
Fixing Your Word VBA Macro: Add Row Below Table Header & Insert Date
Hey there! I see you're learning VBA and ran into a small hiccup with your macro—let's get this sorted out step by step.
The Issue with Your Current Code
Your existing code uses theTable.Rows.Add(theTable.Rows.First) which inserts a new row above the header (first row) instead of below it. Plus, it loops through all tables in the document, but you only need to target the table on the last page (I’m assuming this is the final table in your document).
Corrected VBA Code
Here's the revised macro that does exactly what you need:
Sub AddRowBelowHeaderWithDate() ' Move to the end of the document (matches your original workflow) Selection.EndKey Unit:=wdStory Dim targetTable As Table ' Target the LAST table in the document (since it's on the final page) Set targetTable = ActiveDocument.Tables(ActiveDocument.Tables.Count) Dim newRow As Row ' Insert new row DIRECTLY below the header (first row) ' Inserting before the 2nd row places it right after the header Set newRow = targetTable.Rows.Add(BeforeRow:=targetTable.Rows(2)) ' Insert current date into the second column of the new row ' Adjust the format string (inside Format()) to match your preference (e.g., "mm/dd/yyyy") newRow.Cells(2).Range.Text = Format(Date, "yyyy-mm-dd") ' Optional: Copy header row formatting to the new row for consistency targetTable.Rows(1).Copy newRow.PasteSpecial Paste:=wdPasteFormat End Sub
Key Changes Breakdown
- Target only the final table: Instead of looping through every table, we directly select the last one with
ActiveDocument.Tables(ActiveDocument.Tables.Count)—this ensures we only modify the table on your last page. - Insert row below header: Using
targetTable.Rows.Add(BeforeRow:=targetTable.Rows(2))inserts the new row right before the second existing row, putting it directly beneath your header. - Add date to the second column:
newRow.Cells(2).Range.Text = Format(Date, "yyyy-mm-dd")adds today’s date to the second cell of the new row. Tweak the format string to match your preferred date style. - Optional format sync: The last two lines copy the header’s formatting (fonts, borders, colors) to the new row—remove this if you don’t need matching styles.
Testing the Macro
Run this revised macro, and you’ll get:
- A new row directly below your table’s header
- The second column of this row populated with today’s date in your chosen format
内容的提问来源于stack exchange,提问作者user2817921
相关产品推荐
相关产品推荐

