如何在Excel中使用已定义的名称进行排序?

时间:2014-08-21 17:53:46

标签: excel excel-vba vba

我有一个宏,它使用自定义顺序按类别名称对数据库列进行排序。我不确定是否可行,但我想使用包含所有名为Sorting_List的类别名称的已定义名称。我希望定义名称Sorting_List替换" FL,MF,HF,Furnace Eng,Launder,CM,CM Eng,ML,PP,Lab SOT,Lab AT,SSP,SII,NAPS,ES,FM ,PW,C2H2,CA,Fluids,Fluids Eng,Elec,PMDA,Elec Eng,CH SW,CH SII,CH Std,CH High,CH Elec,CH Eng,CH FS,FS SW,FS SII,FS Elec,Eng ,火车,实验室,实验室SW"因此,如果我更改了定义的名称列表中的任何内容,它将自动更改我的宏。以下是我的代码。非常感谢任何帮助。

  ActiveWorkbook.Worksheets("Database").ListObjects("Database").Sort.SortFields. _
    Add Key:=Range("Database[Category]"), SortOn:=xlSortOnValues, Order:= _
    xlAscending, CustomOrder:= _
    "FL,MF,HF,Furnace Eng,Launder,CM,CM Eng,ML,PP,Lab SOT,Lab AT,SSP,SII,NAPS,ES,FM,PW,C2H2,CA,Fluids,Fluids Eng,Elec,PMDA,Elec Eng,CH SW,CH SII,CH Std,CH High,CH Elec,CH Eng,CH FS,FS SW,FS SII,FS Elec,Eng,Train,Lab,Lab SW" _
    , DataOption:=xlSortNormal

1 个答案:

答案 0 :(得分:1)

Dim sCustomOrder as String
Dim rng as Range
sCustomOrder = ""
For Each rng in ActiveWorkbook.Names("Sorting_List").RefersToRange
    If rng.Text <> "" Then sCustomOrder = sCustomOrder & "," & rng.Text
Next rng

ActiveWorkbook.Worksheets("Database").ListObjects("Database").Sort.SortFields.Add _
    Key:=Range("Database[Category]"), _
    SortOn:=xlSortOnValues, _
    Order:= xlAscending, _
    CustomOrder:= sCustomOrder, _
    DataOption:=xlSortNormal