Got any Excel/VBA Questions? Excel Help
This UDF (User Defined Function) will allow you to nominate a range of colored cells to be sorted by the color order chosen. In other words, Sort by color! This example code sorts by the cells Interior (Background) color. You can also sort by the cells Text color by Replacing Interior with Font.
The Code
Function ColorRank(ColorOrder As Range, LookCell As Range) ''''''''''''''''''''''''''''''''''''''''''''' 'Written by OzGrid Business Applications 'www.ozgid.com 'Ranks a list of Colors so they can be sorted ''''''''''''''''''''''''''''''''''''''''''''' Dim i As Integer Dim ICol1 As Integer Dim ICol2 As Integer i = 1 ICol2 = -1 ColorRank = 0 'Loop until match is found Do Until ICol1 = ICol2 'Replace "Interior" with Font to sort by Font color ICol1 = ColorOrder(i, 1).Interior.ColorIndex ICol2 = LookCell.Interior.ColorIndex If i = ColorOrder.Rows.Count + 1 Then 'No Match found place in Text ColorRank = "No colour match!!!" Exit Do End If 'Pass the Row number of the colour match ColorRank = i i = i + 1 Loop End Function
To use this UDF push Alt+F11 and go Insert>Module and paste in the code. Push Alt+Q and save. The Function will appear under "User Defined" in the Paste Function (Shift+F3).
Use the Function as shown in the graphic example below.
Color Order | Amount | Formula Result | Formula Used | |
200 | 4 | =ColorRank($A$2:$A$7,C2) | ||
100 | 6 | =ColorRank($A$2:$A$7,C3) | ||
955 | 2 | =ColorRank($A$2:$A$7,C4) | ||
500 | 3 | =ColorRank($A$2:$A$7,C5) | ||
1000 | 1 | =ColorRank($A$2:$A$7,C6) | ||
800 | 2 | =ColorRank($A$2:$A$7,C7) | ||
1500 | 1 | =ColorRank($A$2:$A$7,C8) | ||
500 | 3 | =ColorRank($A$2:$A$7,C9) | ||
2000 | 1 | =ColorRank($A$2:$A$7,C10) | ||
100 | 5 | =ColorRank($A$2:$A$7,C11) | ||
20 | No Color match !! | =ColorRank($A$2:$A$7,C12) |
$A$2:$A$7is the Color Order wanted.
Once you have the formulas in, reading from your list and from the "Color Order" list you simply sort your list and the formula results by the "Formula Result" column.
Index to Excel VBA Code |
See also Index to Excel VBA Code and Index to Excel Freebies and Lesson 1 - Excel Fundamentals and Index to how to… providing a range of solutions.
Click here to visit our Free 24/7 Excel/VBA Help Forum where there are thousands of posts you can get information from, or you can join the Forum and post your own questions.