Please, test the next function. It uses arrays (one of them being a helper array, built in the known way to sort chapters) and a Bubble sort an array based on another one and should be very fast. It (now) will return in the next column "B:B", if the range to be sorted in in "A:A"), only to see the output. If it is on your test, you should only adapt the last code line of the testing Sub
:
Function SortChapters(rng As Range)
Dim arr(), helperArr(), arrSplit() As String, i As Long, j As Long
arr = rng.Value2: helperArr = arr 'helperArr will be used as bases for sorting both arrays
'format each cell/array element in a way to be correctly sorted:
For i = 1 To UBound(helperArr)
arrSplit = Split(helperArr(i, 1), ".")
For j = LBound(arrSplit) To UBound(arrSplit)
arrSplit(j) = Format(CLng(arrSplit(j)), String(3, "0"))
Next j
helperArr(i, 1) = Join(arrSplit, ".") ' re-join the array element by "."
Next i
'sort arr based on helperArr:
BubbleSortTwo2D helperArr, arr 'sort arr, based on helperArr
SortChapters = arr
End Function
Private Sub BubbleSortTwo2D(arrRef, arr) 'it sorts arr, based on arrRef!
Dim i As Long, j As Long, temp, temp1
For i = LBound(arrRef) To UBound(arrRef) - 1
For j = i + 1 To UBound(arrRef)
If arrRef(i, 1) > arrRef(j, 1) Then
temp = arrRef(i, 1): arrRef(i, 1) = arrRef(j, 1)
temp1 = arr(i, 1): arr(i, 1) = arr(j, 1)
arrRef(j, 1) = temp: arr(j, 1) = temp1
End If
Next j
Next i
End Sub
It can be tested with the next Sub
:
Sub testSortChapters()
Dim sh As Worksheet, rng As Range, lastR As Long, arr
Set sh = ActiveSheet 'use here the necessary sheet
lastR = sh.Range("A" & sh.rows.count).End(xlUp).row 'last row on A:A
Set rng = Range("A1:A" & lastR)
arr = SortChapters(rng)
rng.Offset(, 1).Value2 = arr
End Sub
As I wrote above, if the code return is convenient, the code line:
rng.Offset(, 1).Value2 = arr
should become:
rng.Value2 = arr
And the code return will be placed in place of the processed range...
The above code should work in any Excel version. If Excel 365, the function can be used as UDF (User Defined Function) and called it from a cell. Placing the next formula in "B1" will return in "B:B":
=SortChapters(A2:A6)
This solution is able to deal with chapters and subchapters up to three digits (999), for each...
Please, send some feedback after testing the code.