2017-04-26 69 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我想使用VBA宏,而不是manullay –

+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