How to create a table using vba?

2019-08-08 15:40发布

问题:

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