excel - 使用 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
解决方案
请尝试下一个代码:
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
属性加载...
推荐阅读
- vue.js - TypeError:state.customerComplaints.add 不是开玩笑单元测试中的函数
- ruby-on-rails - 存在的rails葡萄实体无法正常工作
- java - springboot从2.1升级到2.2后,显示CannotGetJdbcConnectionException
- stripe-payments - Stripe Checkout 未定义变量:响应
- scala - 播放:如果 Action 在其内部被弃用,则获取信息
- prestashop - Prestashop 1.6/1.7:在“web”公共文件夹中的 PHP 脚本中需要“autoload.php”导致错误 500(没有命名空间的脚本)
- javascript - 函数不会在 if else 语句和 for 循环中被提升?
- excel - 如何在 VBA Excel 中创建一个循环以将 2 个单元格中指示的范围之间的值解析为一个新单元格?
- javascript - Fabric JS 多重过滤器处理(更换或添加过滤器)
- arrays - 区分数组/指针以引发编译错误