如何在不调用表名的情况下引用表中的特定列?我想替换===>范围(“Table1 [CODER]”)< ===引用.Listobject索引号或使用我定义的变量“tableName”,但我无法弄清楚任何一个选项的语法。
Public Sub CreateTableAndSortYNG()
Dim tableName As String
With ActiveWorkbook.ActiveSheet
.ListObjects.Add(xlSrcRange, .UsedRange, , xlYes).Name = .Name & "_Table"
tableName = ActiveWorkbook.ActiveSheet.ListObjects(1).DisplayName
MsgBox tableName
.ListObjects(1).Sort.SortFields.Clear
.ListObjects(1).Sort.SortFields.Add Key:=Range("Table1[CODER]"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
.ListObjects(1).Sort.SortFields.Add Key:=Range("Table1[TYPE]"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
.ListObjects(1).Sort.SortFields.Add Key:=Range("Table1[DSCHG_DT]"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
End With
End Sub
答案 0 :(得分:0)
几个笔记。您正在使用With
,但没有充分利用它。此外,您已经掌握了如何在这种情况下使用变量的理论(参见With ActiveWorkbook.ActiveSheet.ListObjects.Add(xlSrcRange, .UsedRange, , xlYes).Name = .Name & "_Table"
)。
这是你的代码,收紧了:
Public Sub CreateTableAndSortYNG()
Dim tableName As String
With ActiveWorkbook.ActiveSheet
.ListObjects.Add(xlSrcRange, .UsedRange, , xlYes).Name = .Name & "_Table"
tableName = .ListObjects(1).DisplayName
'MsgBox tableName ' I removed this because I think you're using this to check the name. I like using the next line instead
Debug.Print tableName ' This will show in the "Immediate Window" in the VB Editor (press CTRL+G) to see the immediate window
With .ListObjects(1).Sort.SortFields
.Clear
.Add Key:=Range(tableName & "[CODER]"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
.Add Key:=Range(tableName & "[TYPE]"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
.Add Key:=Range(tableName & "[DSCHG_DT]"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
End With
End With
End Sub