How do I get cells in Excel that contain IP addresses to sort properly?
As you may have realised, your IP addresses are treated as text and not numbers. They are being sorted as text, which means that addresses beginning with "162" will come before addresses beginning with "20." (because the character "1" comes before the character "2".
You can use the formula provided in this answer: https://stackoverflow.com/a/31615838/4424957 to split the IP address into its parts.
If your IP addresses are in columns A, add columns B-E as shown below.
Enter the formula
=VALUE(TRIM(MID(SUBSTITUTE($A2,".",REPT(" ",999)),(B$1)*999-998,999)))
in cell B2 and copy it to columns B-E in all rows to get the four parts of each IP address. Now sort the whole range by columns B through E (in that order) as shown below:
If you don't want to see the helper columns (B-E), you can hide them.
The most easiest, 3 steps Solution I can suggest you are,,,
Select the IP Address Column, apply Text to Column command.
In adjacent Column write this Formula
=CONCATENATE(B3,".",C3,".",D3,".",E3)
Finally Sort in Ascending order.
Check the Screen Shot.
NB:
Red is Original IP Address (in Column A).
Green after applied Text to Column (Column B to E).
Black is After applied Concatenate & Sorting (Column F).
The reason is very simple originally IP address is Text Data and Excel doesn't accepts any Cell Format to turn it to Number.
Hope this help you.
Here'a a VBA function I wrote some time ago to solve the same problem. It generates a padded version of an IPv4 address which sorts correctly.
Function SortAddress(Address As String) ' format address as XXX.XXX.XXX.XXX to permit sorting
Dim FirstByte As Integer, LastByte As Integer, I As Integer
SortAddress = ""
FirstByte = 1
For I = 0 To 2 ' process the first three bytes
LastByte = InStr(FirstByte, Address, ".") ' find the dot
' append the byte as 3 digits followed by dot
SortAddress = SortAddress & Format(Mid(Address, FirstByte, LastByte - FirstByte), "000\.")
FirstByte = LastByte + 1 ' shift the start pointer
Next I
SortAddress = SortAddress & Format(Mid(Address, FirstByte), "000") ' process the last byte
End Function
Simple example:
Result
Formulas
You can sort by the 'Sortable' column and hide it.