[英]Sort Numbers & Text Separated by Comma in Cell
I am trying to sort a combination of text and numbers.我正在尝试对文本和数字的组合进行排序。 It works for the sorting, but where the cell is correct, it gives me an #VALUE!它适用于排序,但在单元格正确的地方,它给了我一个#VALUE! error.错误。 It also does not populate when it's a single value example PR54.当它是单值示例 PR54 时,它也不会填充。 How do I correct this?我该如何纠正?
Original cell: A1, B13, B15原始单元格:A1、B13、B15
Result receiving: #VALUE!结果接收:#VALUE!
Desired result: A1, B13, B15期望结果:A1、B13、B15
Function StrSort(ByVal sInp As String, _
Optional bDescending As Boolean = False) As String
Dim asSS() As String
Dim sSS As String
Dim n As Long
Dim i As Long
Dim j As Long
asSS = Split(sInp, ",")
n = UBound(asSS)
Dim TemporaryNumberArray() As Double
For i = 0 To n
If IsNumeric(Trim(asSS(i))) Then
On Error Resume Next
If IsError(UBound(TemporaryNumberArray)) Then
ReDim TemporaryNumberArray(0 To 0)
Else
ReDim Preserve TemporaryNumberArray(0 To UBound(TemporaryNumberArray) + 1)
End If
On Error GoTo 0
TemporaryNumberArray(UBound(TemporaryNumberArray)) = asSS(i)
End If
Next
n = UBound(TemporaryNumberArray)
If n < 1 Then
StrSort = sInp
Else
For i = 0 To n - 1
For j = i + 1 To n
If (TemporaryNumberArray(j) < TemporaryNumberArray(i)) Xor bDescending Then
sSS = TemporaryNumberArray(i)
TemporaryNumberArray(i) = TemporaryNumberArray(j)
TemporaryNumberArray(j) = sSS
End If
Next j
Next i
StrSort = CStr(TemporaryNumberArray(0))
For i = 1 To n
StrSort = StrSort & ", " & CStr(TemporaryNumberArray(i))
Next
End If
If n < UBound(asSS) Then
For i = 0 To UBound(asSS)
If Not IsNumeric(asSS(i)) Then
StrSort = StrSort & ", " & asSS(i)
End If
Next
End If
End Function
Thank you in advance!先感谢您!
This worked for me.这对我有用。 You can call SortList
from a worksheet and it will return the sorted list.您可以从工作表中调用SortList
,它会返回排序后的列表。
Function SortList(c) As String
Dim arr, i
arr = Split(c, ",")
For i = LBound(arr) To UBound(arr) 'trim all array elements
arr(i) = Trim(arr(i))
Next i
SortArray arr 'sort in-place
SortList = Join(arr, ",") 'return sorted
End Function
'Sort an array in-place
Sub SortArray(list)
Dim First As Long, Last As Long, i As Long, j As Long, tmp
First = LBound(list)
Last = UBound(list)
For i = First To Last - 1
For j = i + 1 To Last
If DoCompare(Trim(list(i)), Trim(list(j))) Then 'compare the values
tmp = list(j) '...and in the original array
list(j) = list(i)
list(i) = tmp
End If
Next j
Next i
End Sub
'Compare two values and return true if `a` is greater than `b`
' (numeric values are sorted first)
Function DoCompare(a, b) As Boolean
If IsNumeric(a) And IsNumeric(b) Then
DoCompare = CDbl(a) > CDbl(b) 'two numbers
ElseIf IsNumeric(a) Or IsNumeric(b) Then
DoCompare = IsNumeric(b) 'one numeric, one alpha
Else
DoCompare = a > b 'two alphas
End If
End Function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.