在Excel中对单元格中的值进行排序


2

我想知道是否有一种方法可以对在Microsoft Excel单元格中用逗号分隔的值进行排序。例如,我有一个单元格读取“ 49,11”,我希望它显示为“ 11,49”。有任何想法吗?


您将需要VBA来执行此操作,而不更改数据的结构。
Raystafarian 2014年

Answers:


3

考虑以下用户定义函数

Public Function CellSort(r As Range) As String
    Dim bry() As Long, L As Long, U As Long
    ch = r(1).Text
    ary = Split(ch, ",")
    L = LBound(ary)
    U = UBound(ary)
    ReDim bry(L To U)
    For i = LBound(ary) To UBound(ary)
        bry(i) = CLng(ary(i))
    Next i

    Call BubbleSort(bry)

    For i = LBound(bry) To UBound(bry)
        ary(i) = CStr(bry(i))
    Next i
    CellSort = Join(ary, ",")
End Function


Sub BubbleSort(arr)
    Dim strTemp As Variant
    Dim i As Long
    Dim j As Long
    Dim lngMin As Long
    Dim lngMax As Long
    lngMin = LBound(arr)
    lngMax = UBound(arr)
    For i = lngMin To lngMax - 1
        For j = i + 1 To lngMax
            If arr(i) > arr(j) Then
                strTemp = arr(i)
                arr(i) = arr(j)
                arr(j) = strTemp
            End If
        Next j
    Next i
End Sub

1

Excel排序功能可在整个单元格上运行。要在单元格中排序,您需要使用VB脚本。您可能考虑使用“文本到列”将单元格的内容拆分为列,然后进行排序(从左到右)。


确保文本到列,转置和排序效果很好。
Raystafarian 2014年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.