首页 > 解决方案 > 使用 vba 对日期进行排序

问题描述

我在列表框中显示了一个数据列表,单击一个按钮后,该列表出现在我的用户窗体上。我的列表第 2 列有日期,我想进行降序排序。我有下面的代码,但它不起作用,我错了吗?

    fin_col_Form_Init = Ws.Cells(6, 256).End(xlToLeft).Column
    UF_Profil_Edit1.ListBox_Form_Init.ColumnCount = 2
    UF_Profil_Edit1.ListBox_Form_Init.ColumnWidths = "300;100"
    fin_col_Form_Init = Ws.Cells(6, 256).End(xlToLeft).Column
UF_Profil_Edit1.ListBox_Form_Init.ColumnCount = 2
UF_Profil_Edit1.ListBox_Form_Init.ColumnWidths = "300;100"

For i = 2 To fin_col_Form_Init
UF_Profil_Edit1.ListBox_Form_Init.AddItem Ws.Cells(6, i)
UF_Profil_Edit1.ListBox_Form_Init.List(UF_Profil_Edit1.ListBox_Form_Init.ListCount - 1, 1) = Ws.Cells(7, i)
Next i

    Dim y, x As Integer
    Dim MyList As Variant
    
        With UF_Profil_Edit1.ListBox_Form_Init
            For y = 0 To .ListCount - 1
                For x = y To .ListCount - 1
                    If CDate(.List(x, 1)) > CDate(.List(y, 1)) Then
                        For c = 0 To 2
                            MyList = .List(x, c)
                            .List(x, c) = .List(y, c)
                            .List(y, c) = MyList
                        Next c
                    End If
                Next x
    
            .List(y, 2) = Format(.List(y, 2), "####.00")
            Next y
        End With

标签: excelvba

解决方案


请尝试下一个代码:

Sub testSortListBox()
  Dim i As Long, j As Long, sTemp As Date, sTemp2 As String, SortList As Variant
    
    UF_Profil_Edit1.ListBox_Form_Init.ColumnCount = 2
    UF_Profil_Edit1.ListBox_Form_Init.ColumnWidths = "300;100"

    'Store the list in an array to be sorted:
    SortList = UF_Profil_Edit1.ListBox_Form_Init.List
    
    'Sort the array on the second column
    For i = LBound(SortList, 1) To UBound(SortList, 1) - 1
        For j = i + 1 To UBound(SortList, 1)
            If CDate(SortList(i, 1)) < CDate(SortList(j, 1)) Then
                'Swap the second value
                sTemp = SortList(i, 1)
                SortList(i, 1) = SortList(j, 1)
                SortList(j, 1) = sTemp
                
                'Swap the first value
                sTemp2 = SortList(i, 0)
                SortList(i, 0) = SortList(j, 0)
                SortList(j, 0) = sTemp2
            End If
        Next j
    Next i
    
    'Remove the contents of the listbox:
    UF_Profil_Edit1.ListBox_Form_Init.Clear
    'Load the sorted array in the list box:
    UF_Profil_Edit1.ListBox_Form_Init.List = SortList
End Sub

但是,请注意:讨论中的列表框不得链接到范围(不是由其RowSource属性加载...


推荐阅读