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

Excel VBA冒泡排序代码大揭秘!

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

Excel VBA冒泡排序代码大揭秘!

引用
CSDN
11
来源
1.
https://blog.csdn.net/VBAxiaoxueshen/article/details/123495435
2.
https://zhuanlan.zhihu.com/p/587751958
3.
https://blog.csdn.net/aaron19822007/article/details/124647770
4.
https://blog.csdn.net/Eternal_Whispers/article/details/127408919
5.
https://blog.csdn.net/hhhhh_51/article/details/124333750
6.
https://blog.csdn.net/qq_42678477/article/details/107306415
7.
https://blog.csdn.net/adghjkghjkl/article/details/114921391
8.
https://club.excelhome.net/forum.php?mod=viewthread&tid=1212171&extra=&mobile=2
9.
https://club.excelhome.net/thread-1681191-1-1.html
10.
https://club.excelhome.net/thread-1052790-1-1.html
11.
https://www.cnblogs.com/Stefan-Gao/p/14305321.html

在Excel VBA编程中,掌握高效的排序算法是提升工作效率的关键。本文将深入解析如何编写VBA冒泡排序代码,从一维数组到二维数组,逐步介绍升序和降序排列的方法。通过实际案例演示,帮助你轻松掌握这一实用技能,让你的工作更加高效便捷。

01

冒泡排序原理简介

冒泡排序是一种简单的排序算法,通过重复遍历待排序的列表,比较相邻元素,如果顺序错误就交换他们,直到没有需要交换的元素为止。时间复杂度是O(n²),适用于小数据集。

02

一维数组排序实现

基本代码实现

Sub BubbleSort()
    Dim arr As Variant
    Dim i As Long, j As Long
    Dim temp As Variant
    
    ' 示例数组(可根据需要修改)
    arr = Array(5, 3, 8, 6, 2, 7, 1, 4)
    
    ' 外层循环控制遍历次数
    For i = LBound(arr) To UBound(arr) - 1
        ' 内层循环进行相邻元素比较
        For j = LBound(arr) To UBound(arr) - i - 1
            If arr(j) > arr(j + 1) Then
                ' 交换元素
                temp = arr(j)
                arr(j) = arr(j + 1)
                arr(j + 1) = temp
            End If
        Next j
    Next i
    
    ' 输出排序结果到调试窗口
    For i = LBound(arr) To UBound(arr)
        Debug.Print arr(i)
    Next i
End Sub

升序和降序实现

要实现降序排序,只需修改比较条件:

If arr(j) < arr(j + 1) Then

应用到工作表数据

将工作表数据读取到数组中,排序后再输出:

Sub SortWorksheetData()
    Dim arr As Variant
    Dim lastRow As Long
    
    ' 获取数据范围
    lastRow = Cells(Rows.Count, "A").End(xlUp).Row
    arr = Range("A1:A" & lastRow).Value
    
    ' 调用冒泡排序函数
    BubbleSort arr
    
    ' 将排序后的数据输出到B列
    Range("B1:B" & lastRow) = WorksheetFunction.Transpose(arr)
End Sub
03

二维数组排序实现

二维数组的排序需要使用类模块来实现。以下是一个简单的类模块实现:

' 类模块名称:clsBubbleSort
Option Explicit

Private myArray() As Variant
Private mySortColumn As Long
Private myIsAscending As Boolean

Public Property Let Array(arr() As Variant)
    myArray = arr
End Property

Public Property Get Array() As Variant
    Array = myArray
End Property

Public Property Let SortColumn(col As Long)
    mySortColumn = col
End Property

Public Property Get SortColumn() As Long
    SortColumn = mySortColumn
End Property

Public Property Let IsAscending(asc As Boolean)
    myIsAscending = asc
End Property

Public Property Get IsAscending() As Boolean
    IsAscending = myIsAscending
End Property

Public Sub Sort()
    Dim i As Long, j As Long
    Dim temp As Variant
    
    For i = LBound(myArray, 1) To UBound(myArray, 1) - 1
        For j = LBound(myArray, 1) To UBound(myArray, 1) - i - 1
            If (myIsAscending And myArray(j, mySortColumn) > myArray(j + 1, mySortColumn)) Or _
               (Not myIsAscending And myArray(j, mySortColumn) < myArray(j + 1, mySortColumn)) Then
                ' 交换行
                temp = myArray(j, mySortColumn)
                myArray(j, mySortColumn) = myArray(j + 1, mySortColumn)
                myArray(j + 1, mySortColumn) = temp
            End If
        Next j
    Next i
End Sub

使用类模块进行排序:

Sub Sort2DArray()
    Dim arr() As Variant
    Dim sorter As clsBubbleSort
    Dim lastRow As Long
    
    ' 获取数据范围
    lastRow = Cells(Rows.Count, "A").End(xlUp).Row
    arr = Range("A1:B" & lastRow).Value
    
    ' 创建类实例并设置属性
    Set sorter = New clsBubbleSort
    sorter.Array = arr
    sorter.SortColumn = 1 ' 按第一列排序
    sorter.IsAscending = True ' 升序排序
    
    ' 执行排序
    sorter.Sort
    
    ' 输出排序后的数据
    Range("D1:E" & lastRow) = sorter.Array
End Sub
04

错误处理机制

在实际应用中,需要考虑以下错误情况:

  1. 数组为空或数据类型不匹配
  2. 工作表数据范围错误
  3. 内存溢出

错误处理示例:

Sub SafeBubbleSort()
    Dim arr As Variant
    Dim i As Long, j As Long
    Dim temp As Variant
    
    On Error GoTo ErrorHandler
    
    ' 示例数组(可根据需要修改)
    arr = Array(5, 3, 8, 6, 2, 7, 1, 4)
    
    ' 外层循环控制遍历次数
    For i = LBound(arr) To UBound(arr) - 1
        ' 内层循环进行相邻元素比较
        For j = LBound(arr) To UBound(arr) - i - 1
            If arr(j) > arr(j + 1) Then
                ' 交换元素
                temp = arr(j)
                arr(j) = arr(j + 1)
                arr(j + 1) = temp
            End If
        Next j
    Next i
    
    ' 输出排序结果到调试窗口
    For i = LBound(arr) To UBound(arr)
        Debug.Print arr(i)
    Next i
    
    Exit Sub
    
ErrorHandler:
    MsgBox "发生错误:" & Err.Description, vbCritical
End Sub
05

总结和注意事项

冒泡排序虽然简单易懂,但效率较低(时间复杂度O(n²)),只适合处理小规模数据。在实际工作中,如果数据量较大,建议使用更高效的排序算法,如快速排序或Excel自带的排序功能。

在使用VBA排序时,需要注意以下几点:

  1. 数组的索引边界(LBound和UBound)
  2. 数据类型的一致性
  3. 错误处理机制的完善
  4. 大数据量时的性能问题

通过本文的讲解,相信你已经掌握了VBA冒泡排序的基本原理和实现方法。在实际工作中,可以根据具体需求选择合适的排序算法,提高工作效率。

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