问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

Excel VBA排序技巧大揭秘!

创作时间:
作者:
@小白创作中心

Excel VBA排序技巧大揭秘!

引用
CSDN
15
来源
1.
https://blog.csdn.net/Eternal_Whispers/article/details/127408919
2.
https://blog.csdn.net/weixin_38109688/article/details/87655999
3.
https://blog.csdn.net/perfect_red/article/details/110944144
4.
https://blog.csdn.net/zhangdabai1/article/details/135302369
5.
https://blog.csdn.net/aaron19822007/article/details/124647770
6.
https://blog.csdn.net/VBAxiaoxueshen/article/details/123496924
7.
https://jingyan.baidu.com/article/9f63fb91deaa8a89400f0e89.html
8.
https://www.excelhome.net/445.html
9.
https://www.cnblogs.com/eyunkeji/p/16900871.html
10.
https://trumpexcel.com/sort-data-vba/
11.
https://www.cnblogs.com/karkash/p/11982414.html
12.
https://officeguide.cc/excel-vba-array-quick-sort-function-tutorial-examples/
13.
https://www.kdocs.cn/article/A7FFC3E928.html
14.
https://www.cnblogs.com/reakal/p/15548999.html
15.
https://www.cnblogs.com/medik/p/11026422.html

在处理大量数据时,Excel VBA排序功能无疑是提高工作效率的好帮手。无论是随机排序还是自定义顺序快速排序,VBA都能帮你轻松搞定。通过简单的代码示例,你将学会如何利用VBA实现各种复杂的排序需求,让你的数据管理更加高效便捷。快来一起探索这些实用技巧吧!

01

VBA排序基础:Sort函数详解

Excel VBA提供了强大的Sort函数,可以方便地对工作表内容进行排序。Sort函数的基本语法如下:

Range("待排序数据区域").Sort Key1, Order1, Key2, Type, Order2, Key3, Order3,
Header, OrderCustom, MatchCase, Orientation, SortMethod,
DataOption1, DataOption2, DataOption3

各参数的意义如下:

  • Key1、Key2、Key3:排序的关键列(或行)的单元格地址,如Range("A1")。一次Sort最多只能调用3个参数,至少使用1个参数即可。
  • Order1、Order2、Order3:排序的顺序模式指定参数。即:A-Z升序= xlAscending 或直接=1,Z-A降序= xlDescending 或直接=2。
  • Header:是否有标题行参数,一共有3个值:Header:= xlGuess=0 或xlYes=1 或 xlNo=2。
  • MatchCase:是否匹配大小写。MatchCase:=False 、或=0 不区分大小写,MatchCase:=True 、或=1 区分大小写(Case Sensitive)。
  • Orientation:排序方向。一般为同一列中从上到下各行进行排序:Orientation:= xlTopToBottom 、或=1。如果是: 同一行中从左到右各列进行排序,则为:Orientation:= xlLeftToRight、或=2。
  • SortMethod:排序方法。按拼音排序: SortMethod:= xlPinYin 、或=1 (Use phonetic info),按笔画排序: SortMethod:= xlStroke、或=2。

下面是一个简单的示例,演示如何使用Sort函数对工作表进行排序:

Sub SortExample()
    Dim ws As Worksheet
    Set ws = ActiveWorkbook.Sheets("Sheet1")
    
    ' 获取当前表最大行数
    Dim lastRow As Long
    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
    
    ' 对A列进行升序排序
    ws.Range("A1:C" & lastRow).Sort Key1:=ws.Range("A1"), Order1:=xlAscending, Header:=xlYes
End Sub
02

常用排序算法实现

除了使用内置的Sort函数,我们还可以通过VBA实现各种经典的排序算法。这里介绍两种常用的排序算法:冒泡排序和快速排序。

冒泡排序

冒泡排序是一种简单的排序算法,通过重复遍历要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来。

Sub BubbleSort(MyArray() As Variant, ByVal nOrder As Integer)
    Dim i As Long, j As Long
    Dim temp As Variant
    
    For i = LBound(MyArray) To UBound(MyArray) - 1
        For j = i + 1 To UBound(MyArray)
            If (nOrder = 0 And MyArray(i) > MyArray(j)) Or (nOrder = 1 And MyArray(i) < MyArray(j)) Then
                temp = MyArray(i)
                MyArray(i) = MyArray(j)
                MyArray(j) = temp
            End If
        Next j
    Next i
End Sub

快速排序

快速排序是一种高效的排序算法,采用分治策略来把一个序列分为较小和较大的两个子序列,然后递归地排序两个子序列。

Sub QuickSort(arr() As Variant, low As Long, high As Long)
    Dim pivot As Variant
    Dim i As Long, j As Long
    Dim temp As Variant
    
    If low < high Then
        pivot = arr(low)
        i = low
        j = high
        
        Do While i < j
            Do While arr(j) >= pivot And i < j
                j = j - 1
            Loop
            Do While arr(i) <= pivot And i < j
                i = i + 1
            Loop
            If i < j Then
                temp = arr(i)
                arr(i) = arr(j)
                arr(j) = temp
            End If
        Loop
        
        arr(low) = arr(i)
        arr(i) = pivot
        
        QuickSort arr, low, i - 1
        QuickSort arr, i + 1, high
    End If
End Sub
03

随机排序技巧

随机排序在实际工作中有很多应用场景,比如随机安排考试座位、随机分配工作任务等。下面是一个使用Fisher-Yates算法实现的随机排序示例:

Sub ShuffleArray(arr As Variant)
    Dim i As Long, j As Long
    Dim temp As Variant
    
    Randomize
    
    For i = UBound(arr) To LBound(arr) + 1 Step -1
        j = Int((i - LBound(arr) + 1) * Rnd) + LBound(arr)
        temp = arr(j)
        arr(j) = arr(i)
        arr(i) = temp
    Next i
End Sub
04

自定义排序方法

自定义排序允许我们按照特定的顺序对数据进行排序,而不是简单的升序或降序。以下是三种实现自定义排序的方法:

方法1:使用系统自带的OrderCustom

这种方法代码简洁,但自定义序列有字符长度限制(255个)。

Sub CustomSort1()
    Dim rng As Range
    Set rng = Range("E2:E" & Cells(Rows.Count, "E").End(xlUp).Row)
    
    Application.AddCustomList rng
    Dim n As Long
    n = Application.CustomListCount
    
    Range("A:C").Sort Key1:=Range("A1"), Order1:=xlAscending, Header:=xlYes, OrderCustom:=n + 1
    Application.DeleteCustomList n
End Sub

方法2:使用字典+数组+辅助列

这种方法不会破坏单元格的结构,如公式、背景等。

Sub CustomSort2()
    Dim d As Object
    Set d = CreateObject("Scripting.Dictionary")
    
    Dim r As Variant
    r = Range("E2:E" & Cells(Rows.Count, "E").End(xlUp).Row).Value
    
    Dim i As Long
    For i = 1 To UBound(r)
        d(r(i, 1)) = i
    Next i
    
    Dim arr As Variant
    arr = Range("A2:C" & Cells(Rows.Count, 1).End(xlUp).Row)
    
    Dim brr() As Variant
    ReDim brr(1 To UBound(arr), 1 To 1)
    
    For i = 1 To UBound(arr)
        If d.exists(arr(i, 1)) Then
            brr(i, 1) = d(arr(i, 1))
        Else
            brr(i, 1) = "指定序列不存在"
        End If
    Next i
    
    [D:D].Insert
    [D2].Resize(UBound(brr), 1) = brr
    Range("A:D").Sort Key1:=[D1], Order1:=xlAscending, Header:=xlYes
    [D:D].Delete
End Sub

方法3:使用字典+数组+桶排序

这种方法效率最高,但会破坏单元格的结构,如消除公式等。

Sub CustomSort3()
    Dim d As Object
    Set d = CreateObject("Scripting.Dictionary")
    
    Dim r As Variant
    r = Range("E2:E" & Cells(Rows.Count, "E").End(xlUp).Row).Value
    
    Dim i As Long
    For i = 1 To UBound(r)
        d(r(i, 1)) = i
    Next i
    
    Dim arr As Variant
    arr = Range("A2:C" & Cells(Rows.Count, 1).End(xlUp).Row)
    
    Dim brr() As Variant
    ReDim brr(1 To d.Count + 1, 1 To 1)
    
    For i = 1 To UBound(arr)
        If d.exists(arr(i, 1)) Then
            Dim n As Long
            n = d(arr(i, 1))
            brr(n, 1) = brr(n, 1) & "," & i
        End If
    Next i
    
    Dim crr() As Variant
    ReDim crr(1 To UBound(arr), 1 To UBound(arr, 2))
    
    Dim j As Long, k As Long
    For i = 1 To UBound(brr)
        If brr(i, 1) <> "" Then
            j = j + 1
            k = 1
            Dim rowIndices As Variant
            rowIndices = Split(brr(i, 1), ",")
            For Each idx In rowIndices
                crr(j, k) = arr(CLng(idx), k)
                k = k + 1
            Next idx
        End If
    Next i
    
    Range("A2:C" & UBound(crr) + 1) = crr
End Sub

通过以上介绍,相信你已经掌握了VBA中各种排序技巧的实现方法。在实际工作中,你可以根据具体需求选择合适的排序算法和方法,提高数据处理效率。建议初学者先从内置的Sort函数开始学习,逐步掌握各种排序算法的实现原理。

© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号