VBA Code to Change Cell Color

VBA Code to Change Cell Color

Excel supports more than 16 million colors in a cell; hence you should know how to set the exact color in a cell. To do this, you can use RGB (Red, Green, Blue) function in VBA to set the color of a cell. The function requires 3 numbers from 0 to 255 [e.g. RGB(234,232,98)]. Below is a practice code that changes cell colors to Green, Red and Blue.

'This function can be used to change the color of a
cell
Public Sub ChangeCellColor()
    '
    'Change cell color to green
    Sheet1.Range("C4").Interior.Color = RGB(0, 255, 0)
    '
    'Change cell color to red
    Sheet1.Range("C5").Interior.Color = RGB(255, 0, 0)
    '
    'Change cell color to blue
    Sheet1.Range("C6").Interior.Color = RGB(0, 0, 255)
    '
End Sub
To use this code in your Excel file, follow below steps:
  • Open an Excel file
  • Press Alt+F11
  • Insert a Module (Insert>Module) from menu bar
  • Paste the code in the module
  • Now add a shape in Excel sheet
  • Give a name to the shape like ‘Change Cell Color’
  • Right click on the shape and select ‘Assign Macro…’
RGB
  • Select ‘ChangeCellColor’ from the list and click on ‘Ok’ button
  • Done, click on the shape to change the cell colors

You can also read this post to know how to get RGB Codes of a Color.

Author:
Excelsirji.com was started with the thought of making people experience easy while working with Excel, data analytics, vba, automations etc.
Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Are you a Data Enthusiast?

Join us for a ride on your data and automate your stuffs

Business Analytics
Data Analyst
Programming for Data Science
Predictive Analytics for Business