首页 > 解决方案 > VBA对多列和多键数组进行排序

问题描述

我想要一个可以对多列和多个键数组进行排序的函数,即使以牺牲性能为代价,它也应该是动态的。

这个函数应该有3个参数:

  1. 我们要排序的二维数组。
  2. 我们要排序的“列键”数字数组。
  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 列是降序。

笔记:

  1. 该函数不允许使用工作表,它应该是纯 VBA 逻辑。
  2. 无需处理单列数组的场景,只需处理多列数组。
  3. 如果“MyArr”参数不为空,则无需处理输入(参数)的验证。
  4. 空值或任何其他值应该是排序顺序,如 excel 排序顺序,如果 excel 将空值发送到底部,我可以。

标签: arraysexcelvbasorting

解决方案


我解决了它,如果将来有人需要它,这里是代码:

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

推荐阅读