我要做的是在电子表格中选择一个表格,然后根据2个不同的列进行排序
我使用记录宏选项生成了此代码。该表的大小发生了变化,这就是我使用xlDown的原因,不幸的是,代码后来引用了确切的单元格“B4:B52”。知道如何解决这个问题吗?
Range("B4:J4").Select
Range(Selection, Selection.End(xlDown)).Select
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range( _
"B4:B52"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range( _
"G4:G52"), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").Sort
.SetRange Range("B4:J52")
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
答案 0 :(得分:11)
由于您要对Table
(VBA中的ListObject
)进行排序,因此您需要引用它。这将动态调整以包含整个表列。在此示例中,要排序的列标题/名称是“Data1”和“Data3”:
Sub SortTable()
Dim lo As Excel.ListObject
'change this assignment to suit your table location and name
Set lo = ActiveWorkbook.Worksheets("Sheet1").ListObjects("Table1")
With lo
.Sort.SortFields.Clear
.Sort.SortFields.Add _
Key:=Range("Table1[data1]"), SortOn:=xlSortOnValues, Order:=xlAscending, _
DataOption:=xlSortNormal
.Sort.SortFields.Add _
Key:=Range("Table1[data3]"), SortOn:=xlSortOnValues, Order:=xlAscending, _
DataOption:=xlSortNormal
With .Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End With
End Sub
答案 1 :(得分:0)
我会按以下方式对表中的列进行排序:
Sub SortingTable()
Dim ws As Worksheet
set ws = ActiveSheet
Dim target_table As ListObject
Set target_table = ws.ListObjects(wsName)
Dim sort_column_index As Long
sort_column_index = target_table.ListColumns("ColumnToBeSortedName").Index
Dim sort_column As Range
Set sort_column = target_table.ListColumns(sort_column_index).Range
' Applying the sorting to the table
With target_table.Sort
.SortFields.Clear
.SortFields.Add Key:=sort_column _
, SortOn:=xlSortOnValues, Order:=xlAscending _
, DataOption:=xlSortNormal
.Apply
End With
End Sub
实际上,唯一的区别是您声明了一个Range并将其分配给应该排序的特定表列。这样做,您可以将宏应用于不同工作表上的表,假设表中包含名称为#34; ColumnToBeSortedName"的列。