Sort/Remove Duplicate Macro

TrimFunction

New Member
Joined
Jan 9, 2018
Messages
18
I have about 20 columns of unsorted data, and I'm trying to record a macro that sorts (a-z) and removes duplicates without "expanding the selection".

can someone point me in the right place? i searched but was unable to find. thank you!
 

Excel Facts

How to find 2nd largest value in a column?
MAX finds the largest value. =LARGE(A:A,2) will find the second largest. =SMALL(A:A,3) will find the third smallest
Does this work??

Code:
Sub sort_columnsIndividually()
' ~~ Sort columns individually
' https://www.extendoffice.com/documents/excel/4265-excel-sort-multiple-columns-independently.html
'Updateby Extendoffice 20161123

Dim sht As Worksheet
  Set sht = ActiveSheet
  
Dim rng As Range, _
  rngUsed As Range
  Set rngUsed = Application.InputBox(Prompt:="Select range for individual column sort", Type:=8)

Dim lngHdr As Long
  lngHdr = MsgBox("Does your selection contain headers", vbYesNo)
  lngHdr = lngHdr - 5  ' ~~ Converts vbYesNo to xlYesNo
  
  Application.ScreenUpdating = False
  
  For Each rng In rngUsed.Columns
    rng.RemoveDuplicates Columns:=1, Header:=lngHdr
  
    With sht.Sort
      .SortFields.Clear
      .SortFields.Add key:=rng, Order:=xlAscending
      .SetRange sht.Range(rng, rng.End(xlDown))
      .Header = lngHdr
      .MatchCase = False
      .Apply
    End With
  Next rng
  
  Application.ScreenUpdating = True
    
End Sub
 
Last edited:
Upvote 0
Dr. Demento,

You are AMAZING! That code works perfectly.

THANK YOU!

edited: I just ran this on 50 columns/150K rows of data, and it was fast.
now that's what I call "ELEGANT".
 
Last edited:
Upvote 0

Forum statistics

Threads
1,223,895
Messages
6,175,257
Members
452,625
Latest member
saadat28

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top