Skip to content

Instantly share code, notes, and snippets.

@isthisthat
Created June 10, 2016 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isthisthat/d4981fa061fe099b3adc49577a39a677 to your computer and use it in GitHub Desktop.
Save isthisthat/d4981fa061fe099b3adc49577a39a677 to your computer and use it in GitHub Desktop.
Excel macro that colors each unique cell text in a selection with a different color
Sub ColorUniqueInSelection()
'
' Colors each unique cell text in selection with a different color
'
Dim tmp As String
Dim arr() As String
' check selection
If Selection.Cells.Count < 2 Then
MsgBox ("Please select some cells!")
Exit Sub
End If
' get unique values
For Each cell In Selection
If (cell <> "") And (InStr(tmp, cell) = 0) Then
tmp = tmp & cell & "|"
End If
Next cell
If Len(tmp) > 0 Then tmp = Left(tmp, Len(tmp) - 1)
arr = Split(tmp, "|")
' check we have unique values
If UBound(arr) < 1 Then
MsgBox ("All values are the same!")
Exit Sub
End If
' set colors
' list of colors here: https://msdn.microsoft.com/en-us/library/office/ff840443.aspx
ReDim arr_color(UBound(arr) + 1) As Integer
Dim c As Integer: c = 0
For i = 0 To UBound(arr)
c = c + 1
arr_color(i) = c
If c = 56 Then
c = 0
End If
Next i
' set colors
For Each cell In Selection
pos = Application.Match(cell.Value2, arr, False)
cell.Interior.ColorIndex = arr_color(pos)
Next cell
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment