Excel VBA Shade Cell: How to Color Cells with Code
In this article
To shade a cell in Excel using VBA, you use the Interior.Color or Interior.ColorIndex property of a Range object. For example, the simplest line of code to turn cell A1 yellow is Range("A1").Interior.Color = vbYellow. This allows you to automate the visual highlighting of data based on specific conditions, creating dynamic reports that change color as data updates without requiring manual conditional formatting rules.
What You'll Need
- Microsoft Excel installed on a Windows or Mac computer.
- The Developer tab enabled in the Excel Ribbon.
- A basic understanding of how to open the Visual Basic Editor (VBE).
- An Excel workbook saved in the .xlsm (Macro-Enabled Workbook) format to ensure your code is preserved.
Step-by-Step
- Enable the Developer Tab: If you do not see the Developer tab at the top of your Excel screen, right-click any existing tab on the Ribbon and select Customize the Ribbon. In the right-hand list, check the box next to Developer and click OK. (Note: Menu labels may differ slightly depending on your version of Excel).
- Open the Visual Basic Editor: Click the Developer tab and select the Visual Basic button on the far left, or press Alt + F11 on your keyboard. This opens the VBE window where all your macros are written.
- Insert a New Module: In the VBE, go to the top menu and select Insert > Module. This creates a blank white space where you can write your custom procedures. Writing code in a module makes it accessible to the entire workbook.
- Write the Basic Shading Procedure: Type the following code into the module window:
Sub ShadeMyCell() Range("B2").Interior.Color = RGB(255, 0, 0) End SubIn this example,RGB(255, 0, 0)creates a bright red shade. You can change "B2" to any cell address you wish to target. - Experiment with ColorIndex: If you prefer using a predefined palette rather than RGB values, you can use the ColorIndex property. Create another sub-procedure:
Sub ShadeWithIndex() Range("B3").Interior.ColorIndex = 6 End SubColorIndex 6 is standard yellow. There are 56 indexed colors available in the standard Excel palette. - Apply Shading to a Range: To shade multiple cells at once, change the range reference. For example,
Range("B2:D10").Interior.Color = vbGreenwill turn a block of cells green. - Create a Conditional Shading Loop: To shade cells based on their value, use a For Each loop. Copy this example:
Sub ShadeHighValues() Dim cell As Range For Each cell In Range("A1:A20") If cell.Value > 100 Then cell.Interior.Color = vbCyan Else cell.Interior.ColorIndex = xlNone End If Next cell End SubThis code checks every cell from A1 to A20; if the value is over 100, it shades it cyan; otherwise, it removes the shading. - Run the Macro: Return to your Excel sheet. Click the Developer tab, select Macros, choose the name of the macro you just wrote (e.g., "ShadeMyCell"), and click Run.
Common Mistakes
One of the most frequent errors is confusing Color with ColorIndex. The Color property expects a long integer or an RGB value (like RGB(0, 255, 0)), while ColorIndex expects a number between 1 and 56. If you try to put an RGB value into a ColorIndex property, Excel will likely throw a "Run-time error '1004'" because the number is far outside the allowed index range.
Another common mistake is forgetting to clear previous shading. VBA does not automatically "undo" a color when a condition is no longer met. If you run a macro that turns cells red when they are negative, and then the value becomes positive, the cell will stay red until you explicitly tell VBA to remove the color using Interior.ColorIndex = xlNone or Interior.Pattern = xlNone.
Users also often struggle with referencing the correct sheet. If you simply write Range("A1"), VBA applies the color to whatever sheet happens to be active at that moment. This can lead to the wrong cells being shaded if the user has clicked onto a different tab. To prevent this, always qualify your range with a worksheet name, such as Worksheets("Sheet1").Range("A1").Interior.Color = vbBlue.
Tips
For a more professional look, avoid using the basic VBA constants like vbRed or vbBlue, which are often too saturated and harsh for business reports. Instead, use the RGB(red, green, blue) function. By using lower values (e.g., RGB(220, 230, 241)), you can create soft pastel shades that make the spreadsheet easier to read while still highlighting important data.
If you need to find the exact RGB code for a specific color you like, select that cell manually in Excel, go to the Home tab > Fill Color > More Colors > Custom. Note the Red, Green, and Blue values listed at the bottom of the dialog box and plug those numbers directly into your VBA RGB() function.
To speed up your code when shading thousands of cells, disable screen updating at the start of your macro and re-enable it at the end. Use Application.ScreenUpdating = False before your loop and Application.ScreenUpdating = True after. This prevents Excel from flickering and recalculating the visual display every single time a cell changes color, which can reduce the execution time from seconds to milliseconds.
Troubleshooting
If your code runs without error but the cells do not change color, first check if the worksheet is protected. Protected sheets often prevent VBA from modifying cell formatting. You can resolve this by unprotecting the sheet manually or by adding ActiveSheet.Unprotect "YourPassword" at the beginning of your code and ActiveSheet.Protect "YourPassword" at the end.
If you encounter a "Variable not defined" error, it is likely because you have Option Explicit turned on at the top of your module. This is actually a good practice, but it means you must declare every variable. For example, if you use cell in a loop, you must include Dim cell As Range before the loop starts. If you don't want to declare variables, you can remove Option Explicit, though this is not recommended for complex projects.
If the colors appear different than expected, verify that you are not using Conditional Formatting on those same cells. Conditional Formatting rules always take visual precedence over VBA Interior.Color settings. If a cell has a conditional rule that says "Turn red if value < 0", your VBA code to turn the cell blue will be ignored by the Excel display engine as long as the value remains negative.
Frequently Asked Questions
How do I remove the shade from a cell using VBA?
To remove the background color and return the cell to its default state, set the ColorIndex to xlNone. For example: Range("A1").Interior.ColorIndex = xlNone.
Can I use Hex codes for colors in VBA?
VBA does not natively support Hex strings (like "#FFFFFF"). You must convert the Hex code to RGB values or use the Long color value. You can use a converter tool online to find the RGB equivalent of your Hex code.
What is the difference between Color and ColorIndex?
Color allows for millions of combinations using the RGB system, providing total control over the hue. ColorIndex is a limited palette of 56 predefined colors that are easier to reference by a simple number.
How can I shade every other row for better readability?
You can use a loop with a Modulo operator. For example, If i Mod 2 = 0 Then Rows(i).Interior.Color = RGB(240, 240, 240) will shade every even-numbered row in a light gray.
Will these colors print on a physical page?
Yes, colors applied via VBA are treated as standard cell fills and will print as long as your printer is not set to "Black and White" or "Draft" mode in the Page Setup settings.
Can I shade a cell based on a word instead of a number?
Yes. Use a string comparison in your If statement. For example: If cell.Value = "Complete" Then cell.Interior.Color = vbGreen. Ensure the casing matches or use LCase(cell.Value) = "complete" for a case-insensitive check.