arrays - VBA对多列和多键数组进行排序
问题描述
我想要一个可以对多列和多个键数组进行排序的函数,即使以牺牲性能为代价,它也应该是动态的。
这个函数应该有3个参数:
- 我们要排序的二维数组。
- 我们要排序的“列键”数字数组。
- True = Ascending 和 False = Descending 的布尔数组
最后这个函数应该返回排序后的数组。
例如:
Dim SortedArray as Variant
SortedArray = MySuperSortArrayFnc(MyArr, Array(4,1,7), Array(True, False, False))
MyArr = 我要排序的二维源数组。
Array(4,1,7) = 排序的顺序/级别。
Array(True, False, False) = 应该与前面的数组参数平行,所以第 4 列是升序,第 1 列是降序,第 7 列是降序。
笔记:
- 该函数不允许使用工作表,它应该是纯 VBA 逻辑。
- 无需处理单列数组的场景,只需处理多列数组。
- 如果“MyArr”参数不为空,则无需处理输入(参数)的验证。
- 空值或任何其他值应该是排序顺序,如 excel 排序顺序,如果 excel 将空值发送到底部,我可以。
解决方案
我解决了它,如果将来有人需要它,这里是代码:
Public Function SortArr2DM(Arr2D As Variant, aColArr As Variant, IsAscendingArr As Variant) As Variant
Dim I As Long
Dim J As Long
Dim C As Long
Dim X As Byte
'
Dim aCol As Long
Dim TmpValue As Variant
Dim tmpArr As Variant
Dim IsSwitch As Boolean
Dim IsAscending As Boolean
tmpArr = Arr2D
For I = LBound(tmpArr) To UBound(tmpArr)
For J = I + 1 To UBound(tmpArr)
For X = 0 To UBound(aColArr)
aCol = aColArr(X)
IsAscending = IsAscendingArr(X)
If IsAscending Then
If tmpArr(I, aCol) > tmpArr(J, aCol) Then
IsSwitch = True
Exit For
ElseIf tmpArr(I, aCol) < tmpArr(J, aCol) Then
IsSwitch = False
Exit For
End If
Else
If tmpArr(I, aCol) < tmpArr(J, aCol) Then
IsSwitch = True
Exit For
ElseIf tmpArr(I, aCol) > tmpArr(J, aCol) Then
IsSwitch = False
Exit For
End If
End If
Next
If IsSwitch Then
For C = LBound(tmpArr, 2) To UBound(tmpArr, 2)
TmpValue = tmpArr(I, C)
tmpArr(I, C) = tmpArr(J, C)
tmpArr(J, C) = TmpValue
Next
IsSwitch = False
End If
Next
Next
SortArr2DM = tmpArr
End Function
推荐阅读
- python - pyspark 列值是一个列表
- javascript - expo-video-player 在这个简单的库中使用 videoRef
- graphql - 带有打字稿的graphql - @FieldResolver 在compiled-to-js type-graphql 中不起作用
- spring - Kotlin 和 Spring MVC - HTTP 状态 400 - Null
- compilation - Fortran 错误:两个不相关的子例程调用之间的类型不匹配
- python - 只能将 size-1 数组转换为 Python 标量错误消息
- python - 从 txt 输入到列表的数据 - Python
- flutter - 颤动的 TabBarView 有时不会在手势滑动时触发
- javascript - C# 将属性添加到对象列表
- android - kotlin.Collections 似乎没有被导入。“listOf”标记为红色,而在其他项目中工作正常