如何使用 MS Word VBA 中的按钮添加新行?
新行必须复制下拉列表,这应该是所有新行的默认值。
如图所示,当我单击“添加行”按钮时,它必须在表 3 上添加新的 now,包括下拉列表。
目前我有只添加新行而不添加下拉列表的代码。
Private Sub AddRowCommandButton1_Click()
Dim tbl As Table
Dim row As row
Dim cell As cell
Dim combo As FormField
Dim dropDown As ContentControl
Dim i As Integer
' Set the table
Set tbl = ActiveDocument.Tables(3) ' Change the index if your table is not the first table in the document
' Check if a table exists in the document
If tbl Is Nothing Then
MsgBox "No table found in the document.", vbExclamation
Exit Sub
End If
' Check if the specified cell exists in the table
If tbl.Columns.Count < 6 Or tbl.Rows.Count < 2 Then
MsgBox "Table does not have enough rows and columns.", vbExclamation
Exit Sub
End If
tbl.Rows.Add
Set row = tbl.Rows(3)
End Sub
Sub AddRow()
Dim oTbl As Table
Dim lastRow As row
Dim newRow As row
Dim lastCell As cell
Dim newCell As cell
If ActiveDocument.Tables.Count > 2 Then
MsgBox "No target table found in the document.", vbExclamation
Exit Sub
End If
Set oTbl = ActiveDocument.Tables(3)
Set lastRow = oTbl.Rows(oTbl.Rows.Count)
Set lastCell = lastRow.Cells(lastRow.Cells.Count)
lastCell.Select
Selection.InsertRowsBelow 1
Set newRow = oTbl.Rows(oTbl.Rows.Count)
Set newCell = newRow.Cells(newRow.Cells.Count)
lastCell.Range.Copy
newCell.Range.Paste
End Sub
微软文档: