我是 Excel VBA 新手。我倾向于使用 VBA 代码对表中的列进行排序。我的表名称将是动态的。这样就创建了一个字符串。
Sub Macro3()
'
' Macro3 Macro
'
'
Dim TN As String
Range("A11").Select
TN = ActiveCell.ListObject.Name
ActiveWorkbook.Worksheets("Base Unit").ListObjects(TN).Sort.SortFields _
.Clear
ActiveWorkbook.Worksheets("Base Unit").ListObjects(TN).Sort.SortFields _
.Add2 Key:=Range("Base_Unit[[#All],[Cabinet Number]]"), SortOn:= _
xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Base Unit").ListObjects(TN).Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
我想给 .Add2 键范围提供一个字符串 .Add2 Key:=Range("Base_Unit[[#All],[柜号]]"),
有可能吗.
我尝试为 Key Range 命名。但出现错误
ListObject
) 和排序列范围使用(对象)变量。简单
Sub SortTable()
Dim lo As ListObject:
Set lo = ActiveWorkbook.Sheets("Base Unit").Range("A11").ListObject
Dim crg As Range: Set crg = lo.ListColumns("Cabinet Number").Range
With lo.Sort
.SortFields.Clear
.SortFields.Add2 Key:=crg, SortOn:= _
xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
教育性
Sub SortTableStepByStep()
Const SHEET_NAME As String = "Base Unit"
Const TABLE_CELL_ADDRESS As String = "A11"
Const COLUMN_HEADER As String = "Cabinet Number"
Dim wb As Workbook: Set wb = ActiveWorkbook
Dim ws As Worksheet: Set ws = wb.Sheets(SHEET_NAME)
Dim locell As Range: Set locell = ws.Range(TABLE_CELL_ADDRESS)
Dim lo As ListObject: Set lo = locell.ListObject
Dim lc As ListColumn: Set lc = lo.ListColumns(COLUMN_HEADER)
Dim crg As Range: Set crg = lc.Range
With lo.Sort
.SortFields.Clear
.SortFields.Add2 Key:=crg, SortOn:= _
xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub