VBA 使用公式将行插入特定 table 的底部

VBA Insert Rows to bottom of specific table with formula

我有一个包含多个选项卡的电子表格,每个选项卡都有一个 table。我希望每个选项卡都有一个按钮将行插入到 table 的底部(不必 select 一个单元格)并从其上方的行复制公式。 这是我拥有的:

-询问插入多少行 -默认插入为 1 -否则,使用该变量在底部插入并复制公式

Sub InsertRows()
   Dim i As Long
   Dim j As Variant
   j = InputBox("How many rows would you like to add?", "Insert Rows")
   If j = "" Then
      j = 1
   End If
   For i = 1 to j
      Dim newrow As ListRow
      Set newrow = tbl.ListRows.Add
      With newrow.Range
         .Offset(-1).Copy
         .Cells(1).PasteSpecial xlPasteFormulas
         Application.CutCopyMode = False
      End With
    Next
End Sub

我不确定如何从输入到 For 循环中实现 ij

Link 这个宏的按钮应该粘贴在 ModuleThisWorkbook 中 VBA 编辑器


Sub InsertRows()

Dim ws As Worksheet: Set ws = ThisWorkbook.ActiveSheet
Dim i As Long, x As Long
Dim Tbl As ListObject
Dim NewRow As ListRow

i = Application.InputBox("How many rows would you like to add?", "Insert Rows", 1, Type:=1)
Set Tbl = ws.ListObjects(1)

For x = 1 To i
    Set NewRow = Tbl.ListRows.Add(AlwaysInsert:=True)
Next x

End Sub

使用 Application.InputBox 可以设置默认值 (1) 并设置变量类型 (Type:= 1 = numeric) 这将有所帮助通过不允许非数字输入进行数据验证。

请注意,这并未涵盖所有边缘情况,因此您可能仍想添加一些数据验证:例如,有人可以提供负数。在这种情况下,将创建 0 行。用户还可以提供小数,在这种情况下 excel 将舍入到最接近的整数以确定要添加的行数。因此,您可能希望将输入限制为正整数

这是我的方法:

  • 添加一个通用过程以将行添加到 table
  • 通过调整 table 范围的大小添加行
  • 为每个按钮添加宏,在每个按钮中指定 table 的名字

宏:Table1Table2 替换为每个 sheet

的 table 名称
' Macros to associate with buttons
Public Sub InsertRowsInTable1()
    InsertRowsInTable "Table1"
End Sub

Public Sub InsertRowsInTable2()
    InsertRowsInTable "Table2"
End Sub

通用代码:

' Generic procedure to add table rows
Private Sub InsertRowsInTable(ByVal targetTableName As String)
    
    ' Ask user how many rows to ask
    Dim rowsToAdd As Variant
    rowsToAdd = InputBox("How many rows would you like to add?", "Insert Rows", 1)
    
    ' If user didn't input anything, default to 1
    If rowsToAdd = vbNullString Then rowsToAdd = 1
    
    Dim targetTable As ListObject
    Set targetTable = Range(targetTableName).ListObject
    
    ' Resize the table to add rows
    targetTable.Resize targetTable.Range.Resize(targetTable.Range.Rows.Count + rowsToAdd)
        
End Sub