Hi I am new to programming and just started learning VBA for excel. I have a query regarding sorting of arrays. How do I sort an array containing dates? For example if I hav
Your Sort(arr() As Date)
works fine. The problem is with this line
Sort (ThisArray)
Change it to
Sort ThisArray
Also since you are storing Dates
in ThisArray
, I hope you have declared it as Date
?
Example
Sub Sample()
Dim ThisArray(1 To 5) As Date
ThisArray(1) = #12/13/2013#
ThisArray(2) = #12/13/2012#
ThisArray(3) = #12/13/2015#
ThisArray(4) = #12/13/2014#
ThisArray(5) = #12/13/2016#
SortAr ThisArray
For i = 1 To 5
Debug.Print ThisArray(i)
Next i
End Sub
Sub SortAr(arr() As Date)
Dim Temp As Date
Dim i As Long, j As Long
For j = 2 To UBound(arr)
Temp = arr(j)
For i = j - 1 To 1 Step -1
If (arr(i) <= Temp) Then GoTo 10
arr(i + 1) = arr(i)
Next i
i = 0
10: arr(i + 1) = Temp
Next j
End Sub
OUTPUT
13/12/2012
13/12/2013
13/12/2014
13/12/2015
13/12/2016