vba 使用宏(按钮)在excel中添加新行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28097481/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding new row in excel using macro (button)
提问by kkj
I am completely new to macros/VBA. All I am trying to do is to create a button which should add new row. I also want to add data to the new row when the row is created using the button. I copied the code from somewhere and I works fine there but when I try to run it, it gives me error = "Method 'Range' of object '_Worksheet' failed" I believe it is due to the code line:
我对宏/VBA 完全陌生。我想要做的就是创建一个按钮,它应该添加新行。我还想在使用按钮创建行时将数据添加到新行。我从某个地方复制了代码,我在那里工作正常,但是当我尝试运行它时,它给了我错误 =“对象 '_Worksheet' 的方法 'Range' 失败”我相信这是由于代码行:
last_row_with_data = the_sheet.Range(A65536).End(x1Up).Row
The person has done it using simple sub/method but I am doing it with a button
该人使用简单的子/方法完成了它,但我正在使用按钮完成它
Full code is below:
完整代码如下:
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
I don't know whats wrong with code because I am completely new to macros. Anyone please correct the error?
我不知道代码有什么问题,因为我对宏完全陌生。有人请纠正错误吗?
采纳答案by Chrismas007
last_row_with_data = the_sheet.Range(A65536).End(x1Up).Row
should be
应该
last_row_with_data = the_sheet.Range(A65536).End(xlUp).Row
to make it run cleaner, you can use:
为了使其运行更干净,您可以使用:
last_row_with_data = the_sheet.Range("A" & Rows.Count).End(xlUp).Row