使用 FUNCTION 对 Excel VBA 数字和文本数组进行排序 [英] Sort Excel VBA Number and Text Array with FUNCTION

查看:21
本文介绍了使用 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 or,Large to small= 205,101,101,78,38,35,30,23,18,19,12,8,6,4,2,2 如果我有像 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

这篇关于使用 FUNCTION 对 Excel VBA 数字和文本数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆