Excel精英培训网

 找回密码
 注册
查看: 2813|回复: 0

如何在Excel中用VBA进行自定义排序

[复制链接]
发表于 2012-3-20 13:47 | 显示全部楼层 |阅读模式
Excel中默认的排序方法是按照字母或拼音顺序排序的,如果要使用Excel内置的自定义序列或自己添加的自定义序列排序,可参考本站其他文章。本文介绍一下用VBA来实现自定义排序的方法。    一、用工作簿内其他工作表中的序列进行自定义排序
    假如在Book1.xls工作簿的Sheet1表中有如图所示的工资表,现在需要将“姓名”列按Sheet3表B3:B12中的序列排序。
   
   
    在模块中插入下列代码:
    Sub CustomSort1()
      '用指定列中的序列自定义排序
      Dim n As Integer
      n = Application.CustomListCount
      Application.AddCustomList (Worksheets("Sheet3").Range("b3:b12"))
      Range("b3:g12").Sort key1:=Range("b2"), order1:=xlAscending, OrderCustom:=n + 2
      Application.DeleteCustomList n + 1
    End Sub

    说明:
    1. Application.CustomListCount属性返回工作簿中所有自定义序列的数量。从下图的“自定义序列”对话框中可以看到,Excel默认已内置了11个自定义序列。在用户没有添加自定义序列的情况下,Application.CustomListCount的值为11。
   
    n = Application.CustomListCount语句在排序前先取得自定义列表中的自定义序列数量。
    2.  Range.Sort 方法中包含参数“OrderCustom”表明进行自定义排序,同时“OrderCustom”参数的值指明用哪个自定义序列排序。从Excel 2003的“排序选项”对话框中可以看出,默认的排序方法为“普通”,当省略OrderCustom参数或指定其值为1时,则按“普通”(即非自定义序列)方法排序。当使用自定义排序时,将“OrderCustom”参数设置为指定的序列在自定义列表中的顺序加1即可。如自定义序列“一月,二月……,十二月”在下图中的位置为8,如果要用该自定义序列排序,则需指定OrderCustom的值为8。
   
    本例中OrderCustom:=n + 2即OrderCustom:=13(n=11)表示用新增的自定义序列排序。
    3. Application.DeleteCustomList(ListNum)方法删除自定义序列,ListNum指定所删除的自定义序列在自定义序列列表中的位置(不包含“普通”)。本例中新增的自定义序列在自定义列表中处于第12位,由于n=11,Application.DeleteCustomList n + 1将删除新增的自定义序列。
    二、用数组中的序列自定义排序
    下面的代码直接将自定义序列放置在数组中,用Application.AddCustomList 方法添加到自定义列表。
    Sub CustomSort2()
      '用数组中的序列自定义排序
      Application.AddCustomList ListArray:=Array("张梅", "黄中", "李秋霞", "应军军", "孙萍", "刘梅波", "李菲", "吴燕", "艾筱竹", "王佳")
      Range("b3:g12").Sort key1:=Range("b2"), order1:=xlAscending, OrderCustom:=Application.CustomListCount + 1
      Application.DeleteCustomList Application.CustomListCount
    End Sub

    三、用其他工作簿中的某列数据进行自定义排序
   将“ 姓名”列按照同一文件夹中Book2.xls工作簿的"Sheet1"中B3:B12区域中的序列自定义排序。
    Sub CustomSort3()
     '用其他工作簿中的某列数据自定义排序
     Dim wbk As Workbook
     Dim n As Integer
     Dim Arr As Variant
     Application.ScreenUpdating = False
     n = Application.CustomListCount
     Set wbk = GetObject(ThisWorkbook.Path & "\" & "Book2.xls")
     Arr = wbk.Worksheets("Sheet1").Range("b3:b12").Value
     wbk.Close False
     Set wbk = Nothing
     Application.AddCustomList ListArray:=Arr
     Range("b3:g12").Sort key1:=Range("b2"), order1:=xlAscending, OrderCustom:=n + 2
     Application.DeleteCustomList n + 1
     Application.ScreenUpdating = True
    End Sub

    四、用内置的自定义序列排序
    对指定的数据用自定义序列“一月,二月……,十二月”排序:
    Sub CustomSort4()
      '用内置的自定义序列排序
      Range("B21:C32").Sort key1:=Range("b1"), order1:=xlAscending, OrderCustom:=8
    End Sub

您需要登录后才可以回帖 登录 | 注册

本版积分规则

小黑屋|手机版|Archiver|Excel精英培训 ( 豫ICP备11015029号 )

GMT+8, 2024-5-5 01:03 , Processed in 0.199704 second(s), 8 queries , Gzip On, Yac On.

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表