Forum Discussion
williamdhicks
Feb 06, 2023Copper Contributor
Sort fractions within a cell in Excel
I am trying to sort data within a cell (not a column/row) ...and it's in fractions. As an example, I have this in one cell: 1/2;1-1/8;22-12/18;1/8;1/22; I want it reorder the data in th...
HansVogelaar
Feb 06, 2023MVP
Would it be OK to use VBA?
williamdhicks
Feb 06, 2023Copper Contributor
Not familiar with the tool and not sure I could make it work.
- HansVogelaarFeb 06, 2023MVP
I have attached a sample workbook. It is a macro-enabled workbook so you'll have to allow macros when you open it.
The VBA code:
Function SortFractions(ByVal s As String) As String Dim sc As Boolean Dim f1() As String Dim f2() As Double Dim m As Long Dim i As Long Dim j As Long Dim t1 As String Dim t2 As Double s = Trim(s) If Right(s, 1) = ";" Then sc = True s = Left(s, Len(s) - 1) End If f1 = Split(s, ";") m = UBound(f1) ReDim f2(m) For i = 0 To m f2(i) = Evaluate(Replace(f1(i), "-", " ")) Next i For i = 0 To m - 1 For j = i + 1 To m If f2(i) > f2(j) Then t1 = f1(i) f1(i) = f1(j) f1(j) = t1 t2 = f2(i) f2(i) = f2(j) f2(j) = t2 End If Next j Next i SortFractions = Join(f1, ";") & IIf(sc, ";", "") End Function
Press Alt+F11 to view the code.
With a string with multiple fractions in A1, the following formula returns the fractions in ascending order:
=SortFractions(A1)
- williamdhicksFeb 06, 2023Copper ContributorThanks. I tried it in my workbook, but an not that adept at VBA...so it didn't work.
- JosWoolleyFeb 07, 2023Iron Contributor
Alternative for O365:
=LET( ζ, TEXTSPLIT(A1, ";", , 1), γ, ISERR(FIND("-", ζ)), ξ, 0 + IF(γ, "0 " & ζ, SUBSTITUTE(ζ, "-", " ")), TEXTJOIN(";", , SORTBY(ζ, ξ)) )