How can I sort dates in an array in vba?

前端 未结 2 1119
逝去的感伤
逝去的感伤 2020-12-19 09:54

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

相关标签:
2条回答
  • 2020-12-19 10:22

    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 
    
    0 讨论(0)
  • 2020-12-19 10:39

    This might help. fell free to ask a follow up question.

    Sub Sort()
    Dim x As Long, y As Long, z As Long
        For x = Application.WorksheetFunction.Min(Columns("M")) To Application.WorksheetFunction.Max(Columns("M"))
            For y = 1 To Worksheets("Users Info").Cells(Rows.Count, 13).End(xlUp).Row
            If Worksheets("Users Info").Cells(y, 13).Value = i Then
                z = z + 1
                Worksheets("Users Info").Cells(z, 14).Value = i
            End If
            Next y
        Next x
    End Sub
    
    0 讨论(0)
提交回复
热议问题