加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

excel中使用vba对单元格进行排序的方法

(2014-02-14 11:31:54)
分类: 数据分析与算法
VBA中,对范围单元格的排序,是通过Sort方法来实现的。

用法

expression.Sort(Key1, Order1, Key2, Type, Order2, Key3, Order3, _
Header, OrderCustom, MatchCase, Orientation, SortMethod, _
DataOption1, DataOption2, DataOption3)

Key1~3 排序的field。即需要排序的列 or 单元格范围。
Order1~3 顺序or降序。可能值是 顺序 xlAscending,降序 xlDescending
Type 排序种类
Header 是否指定标题行,标题行不参与排序。可能值:xlGuess(Excel自动判断),xlNo(不指定标题行),xlYes(指定标题行)
OrderCustom 定制排序。
MatchCase 是否区分大小写。
Orientation 排序的方向 可能值 xlTopToBottom(行方向优先) xlLeftToRight(列方向优先)
SortMethod 排序方法 可能值包括xlPinYin(拼音排序),xlStroke(笔画排序)
DataOption1~3 Excel2002新追加参数。
实践使用排序。假设有如下数据的Excel。

出席番号 氏名 国語 算数 理科 社会 合計 順位 評価
1001 佐藤 20 51 48 46 165 9 不可
1002 鈴木 56 64 67 59 246 5 良
1003 高橋 89 92 97 81 359 1 優
1004 田中 71 78 75 85 309 4 良
1005 渡辺 25 34 45 54 158 10 不可
1006 伊藤 48 56 42 52 198 7 可
1007 山本 92 88 84 76 340 2 優
1008 中村 84 89 76 84 333 3 良
1009 小林 61 59 65 54 239 6 可
1010 加藤 34 47 38 49 168 8 可
按名字排序

代码

Sub sort1()
  Range("A1:I11").Sort _
    Key1:=Range("B2"), _
    Order1:=xlAscending, _
    Header:=xlGuess, _
    OrderCustom:=1, _
    MatchCase:=False, _
    Orientation:=xlTopToBottom, _
    SortMethod:=xlPinYin, _
    DataOption1:=xlSortTextAsNumbers 'Excel2002 より前のバージョンでは不要
End Sub

按合计高低顺排序

代码

Sub sort3()
  Dim lRow As Long
  Dim lCol As Long
  Dim myRng As Range
    With Worksheets("Sheet1")
      lRow = Cells(Rows.Count, 1).End(xlUp).Row
      lCol = Cells(1, Columns.Count).End(xlToLeft).Column
      Set myRng = .Range(Cells(1, 1), Cells(lRow, lCol))
      myRng.Sort _
        Key1:=.Range("G1"), _
        Order1:=xlDescending, _
        Header:=xlYes, _
        Orientation:=xlTopToBottom
    End With
End Sub

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有