| 
 Excel VBA 數(shù)組排序 作者: parno
 使用EXCEL的VBA編程時(shí),經(jīng)常會用到數(shù)組,有時(shí)需要對數(shù)組進(jìn)行排序,在這里介紹一下數(shù)字?jǐn)?shù)組排序的常用方法以及帶有EXCEL特色的函數(shù)排序方法(所舉例子均以升序排列數(shù)組)。 在介紹具體方法之前,先給個(gè)數(shù)組生成過程。(將數(shù)組a(1 to 50)定義成公用數(shù)組) 復(fù)制內(nèi)容到剪貼板 程序代碼Sub MakeArr()
 For i = 1 To 50
 a(i) = Int(Rnd(1) * 890 + 10)
 Next i
 End Sub
 1、快速排序法
 復(fù)制內(nèi)容到剪貼板 程序代碼Sub FastSort()
 M = 1
 For i = 1 To 49
 If a(i) <= a(i + 1) Then
 If i > M Then
 M = i
 Else
 i = M
 End If
 GoTo kk:
 Else
 x = a(i)
 a(i) = a(i + 1)
 a(i + 1) = x
 If i <> 1 Then i = i - 2
 End If
 kk:
 Next i
 End Sub
 2、冒泡排序法
 復(fù)制內(nèi)容到剪貼板 程序代碼Sub BubbleSort()
 For i = 1 To 49
 For j = i + 1 To 50
 If a(i) > a(j) Then
 TEMP = a(j)
 a(j) = a(i)
 a(i) = TEMP
 End If
 Next j
 Next i
 End Sub
 3、桶排序法
 復(fù)制內(nèi)容到剪貼板 程序代碼Sub Bucket()
 Dim Index
 Dim tempnum
 For i = 2 To 50
 tempnum = a(i)
 Index = i
 Do
 If Index > 1 Then
 If tempnum < a(Index - 1) Then
 a(Index) = a(Index - 1)
 Index = Index - 1
 Else
 Exit Do
 End If
 Else
 Exit Do
 End If
 Loop
 a(Index) = tempnum
 Next
 End Sub
 4、希爾排序法
 復(fù)制內(nèi)容到剪貼板 程序代碼Sub ShellSort()
 Dim skipnum
 Dim Index
 Dim i
 Dim tempnum
 Size = 50
 skipnum = Int((Size / 2)) - 1
 Do While skipnum > 0
 i = 1 + skipnum
 For j = i To 50
 Index = j
 Do
 If Index >= (1 + skipnum) Then
 If a(Index) < a(Index - skipnum) Then
 tempnum = a(Index)
 a(Index) = a(Index - skipnum)
 a(Index - skipnum) = tempnum
 Index = Index - skipnum
 Else
 Exit Do
 End If
 Else
 Exit Do
 End If
 Loop
 Next
 skipnum = (skipnum - 1) / 2
 Loop
 End Sub
 5、選擇排序法
 復(fù)制內(nèi)容到剪貼板 程序代碼Sub SelectionSort()
 Dim Index
 Dim Min
 Dim i
 Dim tempnum
 BzArr
 i = 1
 While (i < 50)
 Min = 50
 Index = Min - 1
 While (Index >= i)
 If a(Index) < a(Min) Then
 Min = Index
 End If
 Index = Index - 1
 Wend
 tempnum = a(Min)
 a(Min) = a(i)
 a(i) = tempnum
 i = i + 1
 Wend
 End Sub
 以上五種排序方法均是數(shù)組排序的常用方法,優(yōu)點(diǎn)是不需借助輔助單元格。執(zhí)行效率視數(shù)組成員的相對有序性的不同而不同。以附件中的50位一維數(shù)組為例,快速排序法的循環(huán)次數(shù)是745次、冒泡法的循環(huán)次數(shù)是1225次、桶排序法的循環(huán)次數(shù)是704次、希爾排序法的循環(huán)次數(shù)是347次、選擇排序法的循環(huán)次數(shù)為1225次。
 下面再介紹兩種用EXCEL函數(shù)的排序方法,一般來說使用EXCEL自帶函數(shù)或方法的執(zhí)行效率會高一些,但限于函數(shù)參數(shù)的限制有的不得不借助于輔助單元格。 6、SMALL函數(shù)法 復(fù)制內(nèi)容到剪貼板 程序代碼Sub SmallSort()
 Dim b(1 To 50)
 For i = 1 To 50
 b(i) = Application.WorksheetFunction.Small(a, i)
 Next
 End Sub
 原數(shù)組不變,生成一個(gè)新的按升序排列的數(shù)組。
 同理也可以用LARGE函數(shù)。我個(gè)人覺得用這種方法較快。
 7、RANK函數(shù)法 復(fù)制內(nèi)容到剪貼板 程序代碼Sub RankSort()
 BzArr
 Dim b(1 To 50)
 For i = 1 To 50
 Sheet2.Cells(i, 1) = a(i)
 Next
 Set rankrange = Sheet2.Range("a1:a50")
 For i = 1 To 50
 For k = 0 To Application.WorksheetFunction.CountIf(rankrange, Sheet2.Cells(i, 1)) - 1
 j = Application.WorksheetFunction.Rank(Sheet2.Cells(i, 1), rankrange, 1)
 a(j + k) = Sheet2.Cells(i, 1)
 Next
 Next
 For i = 1 To 50
 Sheet1.Cells(i + 2, 7) = a(i)
 Next
 End Sub
 此方法的缺點(diǎn)是需要借助輔助單元格。當(dāng)然如果借助輔助單元格的話完全可以用EXCEL的排序功能,在這里就沒必要詳述了。
 |