0

I would like to sort a sheet based on a string for example:

Column 1 Column 2
name1     x
name2     x
name3     asdad
name4     gadfa
name5     gsdff

Is it possible to sort this in a way that it places all rows with a certain string on top, in this case, all rows with the "x" string should be on top first and then it sorts the rest alphabetically based on column 2.

2
  • 2
    Sort records in custom order Commented Jul 29, 2018 at 9:16
  • You can also actually record a macro with this one and edit or remove unnecessary lines :) Commented Jul 29, 2018 at 9:36

1 Answer 1

2

Try this code

Sub Test()
Dim n           As Long

Application.AddCustomList Array("x")
n = Application.CustomListCount

With Sheets("Sheet1")
    .Range("A1").CurrentRegion.Sort Key1:=.Range("B1"), Header:=xlYes, OrderCustom:=n + 1
    .Sort.SortFields.Clear
End With

Application.DeleteCustomList n
End Sub
Sign up to request clarification or add additional context in comments.

2 Comments

When I save the excel file after calling the AddCustomList, it crashes though. What would be the cause of this?
I have added a line to clear the sort in the activesheet. See if this works for you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.