Coloring the content

Colors help us to emphasize the contents of the worksheet, and the VBA allows you to do so through the code. You can change the colors of the font, background or cell border. This can be done in several ways: by specifying a VBA constant representing color, by typing a color code or by specifying a RGB color combination using the same name function …

The color change is made over the selection, therefore it is first necessary to select a cell or group of cells whose attributes we want to change. Then, with the help of the selection, we indicate an object that represents what we want to color. Interior indicates the background of the cell, Font its content, and the Border its border. Finally, using Color or ColorIndex properties, we assign a color value.

For example, if we want to change color of the background for D5 cell, we can perform this in one of three ways:

VBAProject.Sheet1.Range(“D1”).Interior.Color = vbBlue
VBAProject.Sheet1.Range(“D1”).Interior.Color = RGB(0, 0, 255)
VBAProject.Sheet1.Range(“D1”).Interior.ColorIndex = 5

The color is indicated by using the VBA constants, for example: vbBlack, vbWhite, vbBlue … Also, we can do this by specifying its RGB value with the help of appropriate function. Perhaps the easiest way to paint something is by giving the color code, and you can discover the codes by writing a simple VBA program:

Sub Colors()

Dim i As Integer

VBAProject.Sheet1.Cells(1, 1) = “CODE”
VBAProject.Sheet1.Cells(1, 2) = “COLOR”

For i = 1 To 50

VBAProject.Sheet1.Cells(i + 1, 1).Select
VBAProject.Sheet1.Cells(i + 1, 1) = i
VBAProject.Sheet1.Cells(i + 1, 2).Select
Selection.Interior.ColorIndex = i

Next i

End Sub