使用FUNCTION对Excel VBA编号和文本数组进行排序

问题描述:

如果我在单元格A2中有值= 2、4、8、6、12、19、18、23、35、78、101、38、30、205、2我想按单元格B2中的最小到最大或最大到最小排序.那么我的期望结果应该是= 2,2,4,6,8,12,19,18,23,30,35,38,78,101,101,205或(大到小== 205,101,101,78,38,35,30,23,18,19,12,8,6,4,2,2如果我有textvaluse像在A3 = WPN/01,AFF/02,PROP/4,ENG/03中那么我想按字母顺序排序我想要的结果应该在单元格B3 = AFF/02,ENG/03,PROP/4,WPN/1

If I have values in cell A2=2,4,8,6,12,19,18,23,35,78,101,38,30,205,2 And I want to sort by smallest to largest or largest to smallest in cell B2. then my desired result should be =2,2,4,6,8,12,19,18,23,30,35,38,78,101,101,205 or,Large to small= 205,101,101,78,38,35,30,23,18,19,12,8,6,4,2,2 if I have textvaluse like in A3= WPN/01,AFF/02,PROP/4,ENG/03 Then I want to sort alphabetically my desired result should be in cell B3=AFF/02,ENG/03,PROP/4,WPN/1

以下功能将适用于数字,文本和字母数字(数字和文本均包含)字符串.默认srtCriteria设置为0.因此,如果它不为0,则该数组将按升序排序,否则,如果srtCriteria = 1则降序.

Following function will work for numbers, text and alphanumeric (numbers and text both) strings. Default srtCriteria is set to 0. So, if it is 0 or not mentioned the array will be sorted ascending, else if srtCriteria = 1 then descending.

Function SortArr(myString As String, deLmt As String, Optional srtCriteria = 0)
'myString is deLmt seperated string
'srtCriteria is criteria to sort; 0 or nothing for Ascending, Other digit for descending.
Dim Lb As Long, Ub As Long, i As Long, j As Long
Dim arr, reverseArray
Dim strTemp As String

arr = Split(Trim(myString), deLmt)
Lb = LBound(arr)
Ub = UBound(arr)
For i = Lb To Ub - 1
    For j = i + 1 To Ub
        If IsNumeric(arr(i)) = True And IsNumeric(arr(j)) = True Then
            If Val(arr(i)) > Val(arr(j)) Then
            strTemp = arr(i)
            arr(i) = arr(j)
            arr(j) = strTemp
            End If
        Else
            If (arr(i)) > (arr(j)) Then
            strTemp = arr(i)
            arr(i) = arr(j)
            arr(j) = strTemp
            End If
        End If
    Next j
Next i

If srtCriteria = 0 Then
    SortArr = Join(arr, deLmt)
    Else
    ReDim reverseArray(Ub)
        For i = 0 To Ub
            reverseArray(i) = arr(Ub - i)
        Next
    SortArr = Join(reverseArray, deLmt)
End If

End Function