使用宏(按钮)在 excel 中添加新行

Adding new row in excel using macro (button)

我对 macros/VBA 完全陌生。我想要做的就是创建一个应该添加新行的按钮。我还想在使用按钮创建行时将数据添加到新行。 我从某个地方复制了代码并且我在那里工作正常但是当我尝试 运行 它时,它给我错误 = "Method 'Range' of object '_Worksheet' failed" 我相信这是由于代码行:

last_row_with_data = the_sheet.Range(A65536).End(x1Up).Row

这个人用简单的方法做到了 sub/method 但我用的是按钮

完整代码如下:

Private Sub CommandButton1_Click()

Dim the_sheet As Worksheet
Dim table_list_object As ListObject
Dim table_object_row As ListRow
Set the_sheet = Sheets("Sheet1")
Set table_list_object = the_sheet.ListObjects(1)
Set table_object_row = table_list_object.ListRows.Add

table_object_row.Range(1, 1).Value = "12324"

last_row_with_data = the_sheet.Range(A65536).End(x1Up).Row

the_sheet.Range("B" & last_row_with_data) = "Title Name"
the_sheet.Range("C" & last_row_with_data) = "Ref Number"

End Sub

我不知道代码有什么问题,因为我对宏完全陌生。有人请更正错误吗?

last_row_with_data = the_sheet.Range(A65536).End(x1Up).Row

应该是

last_row_with_data = the_sheet.Range(A65536).End(xlUp).Row

要使其运行更干净,您可以使用:

last_row_with_data = the_sheet.Range("A" & Rows.Count).End(xlUp).Row