How to create a table using vba?

一笑奈何 提交于 2019-12-11 10:25:33

问题


I'm writing a simple code to get some key figures from a database import/export. I want to make it user friendly, basically "one buttton click" gives the result.

When I wrote the code, I use Alt+F11 and "Play" => it works. But when I inserted the Active X-Control "CommandButton1_Click" the macro stops.

Here is where (first line):

         ActiveSheet.ListObjects.Add(xlSrcRange, Range("A$1:$Be$1500"), , xlYes).Name = _
    "Table1"

Range("Table1[#All]").Select
ActiveSheet.ListObjects("Table1").TableStyle = "TableStyleLight1"

This is exactly the same code which works with the play button.

I get the error message:

"Run-time Error 1004:

The worksheet range for the table data must be on the same sheet as the table beeing created."

Does anyone have an idea?

An improvement to my code would be, to have the table length variable: There might be more rows in one set, and fewer in another data set.


回答1:


An ActiveX command button is a Control in a Sheet, so you won't have any reference issues using it with your code but you must specify them to use the same code else where.

Tweak this to your need and let me know if it isn't enough :

Dim Ws As Worksheet
Set Ws = ThisWorkbook.Sheets("Sheet_Name")

Ws.ListObjects.Add(xlSrcRange, Ws.Range("A$1:$BE$1500"), , xlYes).Name = "New_Table_Name"
Ws.ListObjects("New_Table_Name").TableStyle = "TableStyleLight1"

Just adjust Sheet_Name and New_Table_Name to your need and that should roll!




回答2:


You must specify the sheet for the source range too, because in a worksheet code module, any unqualified reference to Range or Cells is equivalent to Me.Range or Me.Cells and refers to a range on the sheet containing the code (ie the sheet with the button on in this case):

With ActiveSheet.ListObjects.Add(xlSrcRange, ActiveSheet.Range("A$1:$Be$1500"), , xlYes)
   .Name = "Table1"
   .TableStyle = "TableStyleLight1"
End With


来源:https://stackoverflow.com/questions/33010246/how-to-create-a-table-using-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!