A) 无需帮助栏的用户定义函数
为了能够对大纲数字进行排序,您必须带上各个数值
到一个明确定义的统一数字格式 (例如"00",如果假定默认数字不超过99;注意b)部分中灵活的String()函数)。
这种动态数组方法允许任何 范围定义(加上可选 数字最大值)的参数输入,例如
-
=Outline(A5:A10) 对一列进行排序(默认最大值为 2 位)甚至
-
=Outline(A2:E4, 3) 在多列范围内(明确最大为 3 位)
注意: 已使用 Office 2019+/MS365 的较新动态功能进行测试;
为了向后兼容,您必须更改 TextJoin() 函数,并可能使用 CSE (Ctrl+Shift+Enter) 将 =Outline(...) 作为数组公式输入。
Function Outline(rng As Range, Optional ByVal digits As Long = 2)
'Date: 2022-01-09
'Auth: https://stackoverflow.com/users/6460297/t-m
'a) create unordered 1-dim array from any contiguous range
Dim myFormula As String
myFormula = "TextJoin("","",True," & rng.Address(False, False) & ")"
Dim codes
codes = Split(rng.Parent.Evaluate(myFormula), ",")
'b) add leading zeros via number format
Dim i As Long
For i = LBound(codes) To UBound(codes)
Dim tmp: tmp = Split(codes(i), ".")
Dim ii As Long
For ii = LBound(tmp) To UBound(tmp)
tmp(ii) = Format(CInt(tmp(ii)), String(digits, "0"))
Next ii
codes(i) = Join(tmp, ".") ' join to entire string element
Debug.Print i, codes(i)
Next i
'c) sort
BubbleSort codes ' << help proc BubbleSort
'd) remove leading zeros again
For i = LBound(codes) To UBound(codes)
For ii = 1 To digits - 1 ' repeat (digits - 1) times
codes(i) = Replace(codes(i), ".0", ".")
If Left(codes(i), 1) = "0" Then codes(i) = Mid(codes(i), 2)
Next
Next
'e) return function result
Outline = Application.Transpose(codes)
End Function
帮助程序BubbleSort
Sub BubbleSort(arr)
'Date: 2022-01-09
'Auth: https://stackoverflow.com/users/6460297/t-m
Dim cnt As Long, nxt As Long, temp
For cnt = LBound(arr) To UBound(arr) - 1
For nxt = cnt + 1 To UBound(arr)
If arr(cnt) > arr(nxt) Then
temp = arr(cnt)
arr(cnt) = arr(nxt)
arr(nxt) = temp
End If
Next nxt
Next cnt
End Sub
B) 只是为了好玩:替代单一公式方法 (数字范围有限)
我没有扩展数字格式,而是尝试限制数字显示
通过执行临时十六进制替换。
注意,此方法基于单一公式评估
只允许在 1 到 15 的数字范围内的轮廓子编号(因为数字 10 到 15 被字符 A 到 F 替换),但对于低层次深度可能就足够了!此外,它还包括一个表格Sort() 函数,仅在 Excel 版本 MS365 中可用!
Function Outline(rng As Range)
'Site: https://stackoverflow.com/questions/70565436/how-to-sort-outline-numbers-in-numerical-order
'Date: 2022-01-09
'Auth: https://stackoverflow.com/users/6460297/t-m
'Meth: hex replacements + sort; assuming chapters from (0)1 to 15 (10=A,11=B..15=F)
'Note: allows outline sub-numbers only up to 15! Needs Excel version MS365.
Dim pattern
pattern = String(6, "X") & "Sort(" & String(6, "X") & "$,15,""F""),14,""E""),13,""D""),12,""C""),11,""B""),10,""A"")),""A"",10),""B"",11),""C"",12),""D"",13),""E"",14),""F"",15)"
pattern = Replace(Replace(pattern, "$", rng.Address(False, False)), "X", "Substitute(")
Outline = rng.Parent.Evaluate(pattern)
End Function