简体   繁体   中英

Excel 2016 - Sort value in cell in ascending order

I currently have a cell with some values, separated by commas. I wish to sort them in ascending order.

Sample Input (Value in a single cell):

样本输入图像

Sample Output (Value in a single cell):

样本输出图像

I have seen many answers when it comes to sorting rows and columns, but I can't seem to sort the values in a single cell in ascending order. Is it possible to sort the values in a single cell in ascending order? Or is there a workaround for this?

Some explanation/documentation would be appreciated as I'm a beginner at VBA. Thank you for your help.

Please try to split data in a single cell by comma, then sorting it and combine all of them together?

The comments provide you with numerous ways to sort an array. Rightly or wrongly, I've provided my own flavour on an old VBA topic along with the extended piece of outputting the string in a delimited format. Take it or leave it...!

You should be able to refer to the below function directly from any given cell like you would any built-in function in Excel.

Public Function SplitAndSortAscending(ByVal strText As String, ByVal strDelimiter As String) As String
    Dim arrData() As String, arrNewData() As String, i As Long, x As Long, y As Long
    
    arrData = Split(strText, strDelimiter)
    ReDim arrNewData(UBound(arrData))
    
    For i = 0 To UBound(arrData)
        For x = 0 To UBound(arrNewData)
            If arrData(i) < arrNewData(x) Or arrNewData(x) = "" Then
                For y = UBound(arrNewData) To x + 1 Step -1
                    arrNewData(y) = arrNewData(y - 1)
                Next
                
                arrNewData(x) = arrData(i)
                Exit For
            End If
        Next
    Next
    
    For i = 0 To UBound(arrNewData)
        SplitAndSortAscending = SplitAndSortAscending & strDelimiter & arrNewData(i)
    Next
    
    SplitAndSortAscending = Mid(SplitAndSortAscending, Len(strDelimiter) + 1)
End Function

If you have O365, you can use something like the below to achieve the same sort of thing. Take note, my implementation will take 1.0 and format it as a whole number, ie it will come out as 1 .

=TEXTJOIN(",",TRUE,SORT(FILTERXML("<r><v>" & SUBSTITUTE(A1,",","</v><v>") & "</v></r>","//v")))

The assumption is that the example you provided is in cell A1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM