我有一系列日期,格式为“1801,1802,1803,1710,1711等。 我希望能够按值对它们进行排序,以便最低的值首先例如1710,1711,1801,1802,1803。
这样做的原因是我可以按照正确的顺序将它们放入一个字符串中。
我不知道如何做到这一点,任何帮助将不胜感激。谢谢
答案 0 :(得分:0)
这是一个非常简单的例子:
Sub Nathan()
Dim c As Collection, arr, brr
Dim MyString As String
Set c = New Collection
' Part 1 build Collection
arr = Split("1801,1802,1803,1710,1711", ",")
For Each a In arr
c.Add Val(a)
Next a
' Part 2 put Collection into an array
ReDim brr(1 To c.Count)
For i = 1 To c.Count
brr(i) = c.Item(i)
Next i
' Part 3 sort the array
Call aSort(brr)
' make and output a css
MyString = Join(brr, ",")
MsgBox MyString
End Sub
Public Sub aSort(ByRef InOut)
Dim i As Long, j As Long, Low As Long
Dim Hi As Long, Temp As Variant
Low = LBound(InOut)
Hi = UBound(InOut)
j = (Hi - Low + 1) \ 2
Do While j > 0
For i = Low To Hi - j
If InOut(i) > InOut(i + j) Then
Temp = InOut(i)
InOut(i) = InOut(i + j)
InOut(i + j) = Temp
End If
Next i
For i = Hi - j To Low Step -1
If InOut(i) > InOut(i + j) Then
Temp = InOut(i)
InOut(i) = InOut(i + j)
InOut(i + j) = Temp
End If
Next i
j = j \ 2
Loop
End Sub
考虑使用脚本词典(因为sort已经内置)
修改#1:强>
为避免撰写sort
,您可以使用System.Collection.ArrayList
。以下示例从 A 列中获取数据,对其进行排序,并将结果放在 B 列中:
Sub AsortedAffair()
Dim arr, o As Object, oc As Long, i As Long
arr = Columns(1).SpecialCells(2)
Set o = CreateObject("System.Collections.ArrayList")
For Each a In arr
o.Add a
Next a
o.Sort
oc = o.Count
For i = 1 To oc
Cells(i, 2) = o.Item(i - 1)
Next i
End Sub
从中构建以逗号分隔的字符串同样容易。
请注意,此Item()
属性的索引从零开始,而不是一个。