Excel Workbook | |||||||
---|---|---|---|---|---|---|---|
A | B | C | D | E | |||
1 | Before Sort | After Sort | |||||
2 | Formated as General | ||||||
3 | 1 | 1 | Excel 2007 | ||||
4 | 12 | 2 | |||||
5 | 2 | 5 | |||||
6 | 5 | 7 | |||||
7 | 20 | 8 | |||||
8 | 7 | 9 | |||||
9 | 13 | 12 | |||||
10 | 8 | 13 | |||||
11 | 9 | 20 | |||||
12 | |||||||
13 | |||||||
Sheet1 |
Sort worked for me without using text to columns.
That's because your entries are numbers rather than text. If you format a cell as General and enter a number it will be a number. If you format a cell as Text and enter a number it will be a string. Changing the format to General subsequently won't change what the cell contains (a string), only it's appearance.
That's because your entries are text. Format the cells as General and use Data|Text To Columns to convert to numbers.
Function PadNum(sInp As String, Optional ByVal iLen As Long = 1) As String
' shg 2003-1115
' Expands numbers in a string to iLen characters for sorting; e.g.,
' PadNum("13A1U3", 2) = "13A01U03"
' PadNum("1.2.3.15", 3) = "001.002.003.015"
' Numbers are not shortened below their minimal representation:
' PadNum("1.123.2.3", 2) = "01.123.02.03"
' Returns unpadded values if iLen = 1 or omitted
' PadNum("01.123.02.03") = "1.123.2.3"
' All non-numeric characters are returned as-is
Dim sFmt As String
Dim iChr As Long
Dim sNum As String
Dim sChr As String
Dim bNum As Boolean
sFmt = String(IIf(iLen < 1, 1, IIf(iLen > 15, 15, iLen)), "0")
For iChr = 1 To Len(sInp) + 1 ' the +1 flushes a trailing number
sChr = Mid(sInp, iChr, 1)
If sChr Like "#" Then
bNum = True
sNum = sNum & sChr
Else
If bNum Then
bNum = False
PadNum = PadNum & Format(CDbl(sNum), sFmt)
sNum = vbNullString
End If
PadNum = PadNum & sChr
End If
Next iChr
End Function
---A--- -----B----- --------C---------
1 0-1 00-01 B1: =PadNum(A1, 2)
2 0-2 00-02
3 0-2-1 00-02-01
4 0-2-2 00-02-02
5 0-2-2-1 00-02-02-01
6 0-3 00-03
7 0-4-1 00-04-01
8 ... ...
9 1-X 01-X
10 2-X 02-X
11 etc... etc...