![]() |
配列を並べ替える:Excel VBA入門 |
スポンサードリンク | |
Sub Q_Sort(ByRef myData() As Variant, ByVal L As Long, ByVal U As Long) Dim i As Long Dim j As Long Dim S As Variant Dim Tmp As Variant S = myData(Int((L + U) / 2)) i = L j = U Do Do While myData(i) < S i = i + 1 Loop Do While myData(j) > S j = j - 1 Loop If i >= j Then Exit Do Tmp = myData(i) myData(i) = myData(j) myData(j) = Tmp i = i + 1 j = j - 1 Loop If (L < i - 1) Then Q_Sort myData, L, i - 1 If (U > j + 1) Then Q_Sort myData, j + 1, U End Sub |
Sub myRnd1() Dim N As Double Dim i As Long Dim D Const U = 20 ReDim D(1 To U, 1 To 1) Randomize For i = 1 To UBound(D) N = Int(10 * Rnd + 1) D(i, 1) = N Next i Sheets("Sheet1").Columns("A:A").ClearContents Range("A1").Resize(UBound(D), 1).Value = D End Sub |
Sub Sort01() Dim myData Dim S_Data Dim X() As Variant Dim L As Long Dim U As Long Dim i As Long myData = Range(Cells(1, 1), Cells(Rows.Count, 1).End(xlUp)).Value ReDim X(1 To UBound(myData)) For i = LBound(myData) To UBound(myData) X(i) = myData(i, 1) Next i L = LBound(X) U = UBound(X) Call Q_Sort(X, L, U) ReDim S_Data(1 To U, 1 To 1) For i = L To U S_Data(i, 1) = X(i) Next Range("B:B").ClearContents Range("B1").Resize(UBound(S_Data), 1).Value = S_Data End Sub |
Sub Q_D_Sort() Dim myData Dim S_Data Dim myDic As Object Dim X() As Variant Dim D As Variant Dim L As Long Dim U As Long Dim i As Long myData = Range(Cells(1, 1), Cells(Rows.Count, 1).End(xlUp)).Value ’----重複なしの値をDictionaryで取り出す Set myDic = CreateObject("Scripting.Dictionary") For Each D In myData If Not D = Empty Then If Not myDic.Exists(D) Then myDic.Add D, "" End If End If Next D X = myDic.keys Set myDic = Nothing ’----Q_Sortで並べ替える L = LBound(X) U = UBound(X) Call Q_Sort(X, L, U) ReDim S_Data(1 To U + 1, 1 To 1) For i = L To U S_Data(i + 1, 1) = X(i) Next Range("B:B").ClearContents Range("B1").Resize(UBound(S_Data), 1).Value = S_Data End Sub |
スポンサードリンク
PageViewCounter
Since2006/2/27