Excel

Sorting a range of coloured cells

Ease of Use

Intermediate

Version tested with

97, 2000, 2002 (XP) 

Submitted by:

Bob Phillips

Description:

Provides a technique to sort by colour (color), either the cell colour or the text colour. 

Discussion:

Personally, I have always found Excel's sorting functions limited. There is only the option to sort a range of text in ascending or descending ASCII order. Agreed, there is the custom list sort option, but this is long-winded to setup, and limited. This article provides a technique to sort by colour. The accepted technique (at least by me :-)) for sorting by colour is to add a helper column, and derive the colorindex of the cell in that helper column, and then to sort all columns keyed on the helper column. Excel's built-in sort is then called to sort the columns, using the helper column as the key. The code should be able to sort the colours in ascending or descending order, with or without a heading, etc., just like Excel's built-in sort. It should be noted that this routine only sorts cells manually coloured, it does not work for conditionally formatted cells. That is an enhancement in the pipeline. A sample workbook with the code is provided, and it also has a demo worksheet to prove it in action. 

Code:

instructions for use

			

'---------------------------------------------------- ' Sheet1 code module '---------------------------------------------------- ' Function: Procedures to respond to the buttons ' on the demo worksheet ' cmdSortCell ' calls the sort procedure for cell ' colour ' cmdSortText ' calls the sort procedure for text ' colour ' cmdCellReset ' resorts the cell colour data to ' start point ' cmdSortText ' resorts the text colour data to ' start point '---------------------------------------------------- Option Explicit Private Sub cmdCellReset_Click() Range("C6:D14").Sort Key1:=Range("D6"), _ Order1:=xlAscending, _ Header:=xlNo, _ OrderCustom:=1, _ MatchCase:=False, _ Orientation:=xlTopToBottom Range("B2").Select End Sub Private Sub cmdTextReset_Click() Range("H6:I14").Sort Key1:=Range("I6"), _ Order1:=xlAscending, _ Header:=xlNo, _ OrderCustom:=1, _ MatchCase:=False, _ Orientation:=xlTopToBottom Range("B2").Select End Sub Private Sub cmdSortCell_Click() SortByColour Range("C6:D14"), Range("C6") End Sub Private Sub cmdSortText_Click() SortByColour Range("H6:I14"), Range("H6"), False End Sub '---------------------------------------------------- ' End of Sheet1 code module '---------------------------------------------------- '---------------------------------------------------- ' mSortByColour code module '---------------------------------------------------- ' Function: Sorts the range by colour ' Arguments: SortData ' the range to sort ' ByCell ' True to sort cell colour, ' False to sort text colour ' Key1 ' First sort field as Range object ' Order1 ' 1 or 2 for ascending/descending ' Key2 ' Second sort field as Range object ' Order2 ' 1 or 2 for ascending/descending ' Key3 ' Third sort field as Range object ' Order3 ' 1 or 2 for ascending/descending ' Header ' 1 or 2 for yes/no '---------------------------------------------------- Option Explicit Sub SortByColour(SortData As Range, _ Key1 As Range, _ Optional ByCell As Boolean = True, _ Optional Order1 = xlAscending, _ Optional Key2 As Range, _ Optional Order2 = xlAscending, _ Optional Key3 As Range, _ Optional Order3 = xlAscending, _ Optional Header = xlNo) Dim cell As Range Dim rngData As Range Dim rngToSort As Range Dim rngKey1 As Range 'stop screen flashing Application.ScreenUpdating = False 'insert a helper column to insert calculated colorindex 'and set the primary sort key to first cell in that range Key1.Cells(1, 2).EntireColumn.Insert Set rngKey1 = Key1.Cells(1, 2) 'setup the sort range, including or excluding the header row If Header = xlYes Then Set rngData = Key1.Cells(2, 1).Resize(SortData.Rows.Count, 1) Else Set rngData = Key1.Cells(1, 1).Resize(SortData.Rows.Count, 1) End If 'calculate the colorindex for each cell in the sort range 'checking if we need to get cell colour or text colour For Each cell In rngData cell.Offset(0, 1).Value = IIf(ByCell, cell.Interior.ColorIndex, cell.Font.ColorIndex) Next cell 'now sort the data on the primary key supplied, and key2 and key3 if 'applicable Select Case True Case Not Key2 Is Nothing And Not Key3 Is Nothing: SortData.Sort Key1:=rngKey1, _ Order1:=Order2, _ Key2:=Key2, _ Order2:=Order2, _ Key3:=Key3, _ Order3:=Order3, _ Header:=Header Case Not Key2 Is Nothing: SortData.Sort Key1:=rngKey1, _ Order1:=Order2, _ Key2:=Key2, _ Order2:=Order2, _ Header:=Header Case Else: SortData.Sort Key1:=rngKey1, _ Order1:=Order1, _ Header:=Header End Select 'remove the helper column that we previously inserted SortData.Cells(1, 2).EntireColumn.Delete 'tidy up Set cell = Nothing Set rngData = Nothing Set rngToSort = Nothing Set rngKey1 = Nothing Application.ScreenUpdating = True End Sub '---------------------------------------------------- ' End of mSortByColour code module '----------------------------------------------------

How to use:

  1. Open an Excel workbook
  2. Select Tools/Macro/Visual Basic Editor
  3. In the VBE window, select Tools/Project Explorer
  4. Select the Sheet1 module
  5. Copy and paste the 'Sheet1' code section above into this module
  6. Select Insert/Module (this creates module1)
  7. Go to View/Properties.
  8. In the properties pane, select module1 and name it: mSortByColour,
  9. Copy and paste the 'mSortByColour' code section above to that module
  10. Now select File/Save for your file
  11. Click the X (top-right in the VBE window) to return to Excel
 

Test the code:

  1. Download the demo workbook and play with that, OR
  2. Create test data
  3. - colour cells C6:C14 with a variety of cell colours
  4. - set the cells D6:D14 to the numbers 1 to 9
  5. - enter text in cells H6:H14
  6. - set the text colour of cells H6:H14 to a variety of colours
  7. - set the cells I6:I14 to the numbers 1 to 9
  8. Add some run buttons
  9. - ensure that the 'Control Toolbox' toolbar is active (menu Tools>Customize>Toolbars, and ensure that 'Control Toolbox' is checked)
  10. - enter design mode - click the blue-green triangle icon on the 'Control Toolbox' toolbar
  11. - click the 'CommandButton' icon on the 'Control Toolbox' toolbar, and draw a button on the worksheet
  12. - double-click the new button, this will open a code pane in the VB IDE, and then change the button's name to 'cmdSortCell' and its caption to 'Cell Colour'
  13. - go back to Excel and add another button
  14. - double-click the new button, this will open a code pane in the VB IDE, and then change the button's name to 'cmdSortText' and its caption to 'Text Colour'
  15. - exit design mode
  16. Test by clicking either button.
 

Sample File:

xld.SortByColour.zip 18.72KB 

Approved by mdmackillop


This entry has been viewed 289 times.

Please read our Legal Information and Privacy Policy
Copyright @2004 - 2020 VBA Express