2017-04-26 5 views
-1

次のコードを使用してワークシートのセル内のデータをソートしますが、大量のデータでは時間がかかります。 ?VBAを使用してデータのソートを高速化する方法

使用されるコードは次のとおりです。

Sub VBA_DataSorting() 
Dim i As Integer 
Dim j As Integer 
Dim temp As Double ' must be double to contain fractional values 
Dim rng As Range 
Set rng = Range("A1").CurrentRegion 'Range of data to be sorted 
For i = 1 To rng.count 
    For j = i + 1 To rng.count 
    If rng.Cells(j) < rng.Cells(i) Then ' sort smallest to largest 
    'swap numbers 
    temp = rng.Cells(i) 
    rng.Cells(i) = rng.Cells(j) 
    rng.Cells(j) = temp 
    End If 
Next j 
Next i 
End Sub 
+0

は、なぜあなたは、ツールバーからソート機能に組み込まれて使用していませんか? –

+0

@Scott Craner私はmanullayではなくVBAマクロを使いたい –

+4

次に、 'range.sort'メソッドを使います。 –

答えて

0
sub SortDataExample() 

'Building data to sort on the active sheet. 
Range("A1").Value = "Name" 
Range("A2").Value = "Bill" 
Range("A3").Value = "Rod" 
Range("A4").Value = "John" 
Range("A5").Value = "Paddy" 
Range("A6").Value = "Kelly" 
Range("A7").Value = "William" 
Range("A8").Value = "Janet" 
Range("A9").Value = "Florence" 
Range("A10").Value = "Albert" 
Range("A11").Value = "Mary" 
MsgBox "The list is out of order. Hit Ok to continue...", vbInformation 

'Selecting a cell within the range. 
Range("A2").Select 

'Applying sort. 
With ActiveWorkbook.Worksheets(ActiveSheet.Name).Sort 
.SortFields.Clear 
.SortFields.Add Key:=Range("A2:A11"), _ 
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal 
.SetRange Range("A1:A11") 
.Header = xlYes 
.MatchCase = False 
.Orientation = xlTopToBottom 
.SortMethod = xlPinYin 
.Apply 
End With 
MsgBox "Sort complete.", vbInformation 

End Sub 
関連する問題