Change Cell Color Based on HTML Index Value

Question:

Suppose we want to change background and font color of cells in a finite range as user enters any value into the cell.

Let's assume the range is B8 : G15 where we want to apply this logic.

When we enter any number b/w 1 to 56, the cell color should change treating it as index value.




Answer: 

1. Open VBA Editor and open sheet's object.
2. Copy-Paste this code there.



Private Sub Worksheet_Change(ByVal Target As Range)

    If Target.Row >= 8 And Target.Row <= 15 And Target.Column >= 2 And Target.Column <= 7 Then
        If Target.Cells.Count = 1 Then
            If Target.Value >= 0 And Target.Value <= 56 Then
                Target.Interior.ColorIndex = Target.Value
                Target.Font.ColorIndex = Target.Value
            End If
        Else
            For Each cell In Target
                If cell.Value >= 0 And cell.Value <= 56 Then
                    cell.Interior.ColorIndex = cell.Value
                    cell.Font.ColorIndex = cell.Value
                End If
            Next
        End If
    End If

End Sub