Categories: Excel

Excel VBA 陣列快速排序教學與範例

自行定義快速排序演算法 VBA 巨集函數,處理各種陣列排序問題。

在 Excel VBA 中並沒有提供陣列排序的函數可用,如果想要對陣列的元素進行排序,可以自己定義一個快速排序演算法函數來處理。

另外對於資料量比較小的情況,也可以考慮簡單的泡沫排序法,這個可以參考 VBA 泡沫排序教學

快速排序 VBA 巨集函數

以下是一段根據速排序演算法所實作的排序函數:

' 快速排序函數
Public Sub QuickSort(vArray As Variant, inLow As Long, inHi As Long)
  Dim pivot   As Variant
  Dim tmpSwap As Variant
  Dim tmpLow  As Long
  Dim tmpHi   As Long

  tmpLow = inLow
  tmpHi = inHi

  pivot = vArray((inLow + inHi)  2)

  While (tmpLow <= tmpHi)
     While (vArray(tmpLow) < pivot And tmpLow < inHi)
        tmpLow = tmpLow + 1
     Wend

     While (pivot < vArray(tmpHi) And tmpHi > inLow)
        tmpHi = tmpHi - 1
     Wend

     If (tmpLow <= tmpHi) Then
        tmpSwap = vArray(tmpLow)
        vArray(tmpLow) = vArray(tmpHi)
        vArray(tmpHi) = tmpSwap
        tmpLow = tmpLow + 1
        tmpHi = tmpHi - 1
     End If
  Wend

  If (inLow < tmpHi) Then QuickSort vArray, inLow, tmpHi
  If (tmpLow < inHi) Then QuickSort vArray, tmpLow, inHi
End Sub

這個 QuickSort 函數的使用方式為:

QuickSort 陣列, 索引下限值, 索引上限值

最常見的用法是用 LBoundUBound 自動算出陣列索引的上下限, 傳給 QuickSort 排序整個陣列:

QuickSort arr, LBound(arr), UBound(arr)

數值陣列排序

以下是一個單的排序數值應用範例:

Sub Test()
  ' 建立測試用陣列
  Dim arr As Variant
  arr = Array(2, 5, 4, 1, 3)

  ' 對陣列進行排序
  QuickSort arr, LBound(arr), UBound(arr)

  ' 輸出結果
  For i = LBound(arr) To UBound(arr)
    Debug.Print "元素 " & i & " = " & arr(i)
  Next i
End Sub

在這段程式碼當中,當我們呼叫完 QuickSort 函數之後,arr 陣列中的元素就會變成排序好的狀態,然後我們再用一個 For 迴圈配合 Debug.Print 輸出陣列的內容,執行值記得要打開「及時運算視窗」(快速鍵為 Ctrl + g),這樣才能看到輸出的結果。

VBA 數值陣列排序

文字陣列排序

這一個 QuickSort 函數並沒有限制陣列的資料型態,如果陣列的元素是文字,它就會依照字母順序排序:

Sub Test()
  ' 建立測試用陣列
  Dim arr As Variant
  arr = Array("Red", "Yellow", "Green", "Blue")

  ' 對陣列進行排序
  QuickSort arr, LBound(arr), UBound(arr)

  ' 輸出結果
  For i = LBound(arr) To UBound(arr)
    Debug.Print "元素 " & i & " = " & arr(i)
  Next i
End Sub

執行的結果如下:

VBA 文字陣列排序

參考資料:Stack Overflow

Share
Published by
Office Guide
Tags: VBA

Recent Posts

Python 使用 PyAutoGUI 自動操作滑鼠與鍵盤

本篇介紹如何在 Python ...

9 個月 ago

Ubuntu Linux 以 WireGuard 架設 VPN 伺服器教學與範例

本篇介紹如何在 Ubuntu ...

9 個月 ago

Linux 網路設定 ip 指令用法教學與範例

本篇介紹如何在 Linux 系...

9 個月 ago

Windows 使用 TPM 虛擬智慧卡保護 SSH 金鑰教學與範例

本篇介紹如何在 Windows...

10 個月 ago

Linux 以 Shamir’s Secret Sharing 分割保存金鑰教學與範例

介紹如何在 Linux 中使用...

11 個月 ago

Linux 以 Cryptsetup、LUKS 加密 USB 隨身碟教學與範例

介紹如何在 Linux 系統中...

11 個月 ago