我想知道是否有办法对 Microsoft Excel 中单元格内以逗号分隔的值进行排序。例如,我有一个单元格显示“49, 11”,我希望它显示为“11, 49”。有什么想法吗?
答案1
考虑以下用户定义函数:
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
答案2
Excel 排序功能适用于整个单元格。要对单元格进行排序,您需要使用 VB 脚本。您可以考虑使用“文本分列”将单元格的内容拆分为列,然后进行排序(从左到右)。