How to Change Cell Color in VBA

Iqra Hasnain Feb 15, 2024
How to Change Cell Color in VBA

This article will discuss how to change cell color in VBA.

Use the Interior Method to Change Cell Color in Excel VBA

We can change the background colors in excel VBA easily. We can utilize the interior property to return an interior object.

Then we will use the ColorIndex property of the Interior item to set the foundation and background color of the cell. There are three command buttons on the worksheet.

If we want to fill the cell background with a color, we can use the Interior method of the range. We can use the ColorIndex to specify the color code.

Code:

# VBA
Sub changeColor()
Range("B1").Interior.ColorIndex = 37
End Sub

Output:

change cell color in VBA using interior method

If we want to remove the background color of the cell, we can specify the ColorIndex as 0, which acts as a No Fill.

Code:

# VBA
Sub changeColor()
Range("B1").Interior.ColorIndex = 0
End Sub

Output:

remove background color of the cell

We can also get the ColorIndex of any cell by using the following code.

Code:

# VBA
Sub changeColor()
MsgBox Selection.Interior.ColorIndex
End Sub

Select A1 call, and we will click the command button.

Output:

get the ColorIndex of any cell in VBA

The ColorIndex property shows access to a color palette of 56 colors. If we can’t find the specific color, we will use the Color property and RGB function.

Code:

#VBA
Range("B1").Interior.Color = RGB(255, 125, 125)

This RGB stands for Red, Green, and Blue. These are the primary colors.

Every component can take a value from 0 to 255(RGB(255,125,125). With this function, we can make every color.

Output:

Use color property and RGB function to change cell color

Related Article - VBA Cell