1

I am trying to create an Excel 2010 spreadsheet with a button that will create a new sheet and copy sheet 1 to it. I have everything figured out except that the sheets contain tables. When the sheet is copied, the tables are renamed since you cannot have 2 tables with the same name. The VBA scripting I have put together has a section where it needs to select the header row of the table.

Private Sub Worksheet_Change(ByVal Target As Range)
Dim KeyCells As Range
Set KeyCells = ActiveSheet.Range("C2")
If Not Application.Intersect(KeyCells, Range(Target.Address)) _
       Is Nothing Then
    If ActiveSheet.Range("C2") = "KeyWord" Then
        ActiveSheet.ListObjects(1).Range("Table1[[#Headers],[Product]]").Select
        Selection.AutoFilter
        ActiveSheet.ListObjects(1).Range.AutoFilter Field:=6, Visibledropdown:=False, Criteria1:= _
        Array("All", "AS", "ASD", "ASDF"), Operator:=xlFilterValues
        ActiveSheet.Range("C3").Select
        ActiveSheet.Name = ActiveSheet.Range("C2")
    End If
End If
End Sub

I can get around the table renaming by using "ActiveSheet.ListObjects(1)" to specify the first table on the sheet, but when specifying the range to select the headers, I cannot find a way to specify the current name of the first table on the page.

.Range("Table1[[#Headers],[Product]]").Select

I have tried to concatenate it using a variable set by specifying the first cell of the header of the table, but concatenate seems to require a "text" value before you can specify a variable.

Another thought was to store the current name of the table somewhere, change the name of the table to a static value, run the code I need to run then change the table name back to the old unique name. I couldn't figure out a good way of doing that though.

Since the sheet has potential to be copied multiple times, and the name of the table will change each time, I need a method of specifying the table name inside the Range() command without setting it to a specific name.

Any help would be greatly appreciated.

4

2 回答 2

1

我不确定您需要实现什么,但表名可用作:

ActiveSheet.ListObjects(1).DisplayName

您可以将其存储在字符串变量中。

您可以选择表格,包括标题,使用:

ActiveSheet.ListObjects(1).Range.Select

但是请记住,通常不需要选择表格(有或没有标题行)。

于 2013-07-22T18:25:46.140 回答
0

您可以从更多面向对象的编程中受益,这将允许 VBE 中的脚本辅助功能。

任何人,一张桌子是一个ListObject,有一个DataBodyRange,还有一个HeaderRowRange

你想参考HeaderRowRange.

或者,您可以简单地AutoFilter在 table 上使用该方法ListObject

ActiveSheet.ListObjects(1).Range.AutoFilter Field:=6, Visibledropdown:=False, Criteria1:= _
    Array("All", "AS", "ASD", "ASDF"), Operator:=xlFilterValues
于 2013-07-22T18:26:36.827 回答