In Excel VBA, set a cell’s fill color with Range("A1").Interior.Color = RGB(255, 0, 0); the three numbers are red, green, and blue values from 0 to 255. For most VBA work, use the RGB function or a workbook theme color rather than relying on a legacy color index.
What an Excel VBA color code means
“Excel VBA color code” can refer to a few different ways of identifying a color. The most straightforward is an RGB value: three channel values representing red, green, and blue. For example, RGB(255, 0, 0) is red, RGB(0, 0, 0) is black, and RGB(255, 255, 255) is white. Each channel can be any whole number from 0 through 255, giving many possible combinations.
VBA’s RGB(red, green, blue) function returns a Long integer that Excel can use as a color value. You usually do not need to calculate or memorize that integer: supply the three readable channel values to RGB and assign the result to a color property. This works for fills, text, borders, and other formatting objects that expose a Color property.
A web color such as #2E75B6 is written in hexadecimal as red, green, and blue pairs. Its VBA equivalent is RGB(46, 117, 182). Do not assign the text “#2E75B6” directly to .Color; convert the hex pairs into decimal channel values first. RGB is generally clearer to read and maintain in a macro.
Set a cell or range fill color
For cell background color, use the range’s Interior.Color property. The following macro colors cells A1:A10 on a worksheet named Sheet1 with a medium blue. Change the sheet name, range, and RGB values to fit the workbook. Before running any macro, save a copy of the workbook: VBA changes cannot be reversed with Ctrl+Z.
Sub ColorRangeBlue()
Dim target As Range
' Set the cells to format on the named worksheet.
Set target = ThisWorkbook.Worksheets("Sheet1").Range("A1:A10")
' Apply a blue fill using red, green, and blue channels.
target.Interior.Color = RGB(46, 117, 182)
End Sub
To color text instead of the cell background, use Font.Color. For a border, use a specific border’s Color property, such as Range("A1").Borders(xlEdgeBottom).Color. These properties affect different parts of the cell, so changing Interior.Color will not change the font or border.
On Excel for Microsoft 365 for Windows, open the VBA editor with Alt+F11, or choose Developer > Visual Basic if the Developer tab is visible. If it is hidden, enable it under File > Options > Customize Ribbon. Excel for the web can open a workbook containing VBA but cannot create, edit, or run VBA macros. Excel for Mac supports VBA in the desktop application; its keyboard shortcut can depend on the keyboard and function-key settings, so use the Visual Basic command in the ribbon if Option+F11 does not open the editor.
Use colors conditionally in a macro
A macro can choose a color based on a cell’s value. This is useful when a process needs to apply formatting at a particular point, such as marking rows after an import. This example colors cells in A2:A20 green when their value is exactly “Paid,” and removes the fill for other values. It assumes the sheet is named Sheet1.
Sub ColorPaidCells()
Dim ws As Worksheet
Dim cell As Range
' Use the worksheet that contains the status values.
Set ws = ThisWorkbook.Worksheets("Sheet1")
' Apply or clear the fill for each status cell.
For Each cell In ws.Range("A2:A20")
If cell.Value = "Paid" Then
cell.Interior.Color = RGB(198, 239, 206)
Else
cell.Interior.Pattern = xlNone
End If
Next cell
End Sub
This checks for an exact match, so “paid” or “Paid ” with a trailing space will not match “Paid.” If the source data is inconsistent, clean it or adjust the comparison to handle case and extra spaces. Also consider whether a formula or conditional formatting rule is a better fit: unlike a macro that writes a fill, conditional formatting can update the appearance automatically when a value changes.
RGB, hexadecimal, and ColorIndex compared
RGB is usually the best choice for a fixed custom color because it is readable, widely supported, and independent of the old indexed palette. Use three decimal channel values in the order red, green, blue. If a design guide supplies a hexadecimal code, split it into its three two-character pairs and convert each pair from base 16 to decimal. For instance, #2E75B6 becomes red 46, green 117, and blue 182.
ColorIndex is a different system. It refers to a position in Excel’s indexed color palette, rather than directly specifying three color channels. Older Excel workbooks used a palette of 56 colors, and palette behavior can vary with workbook settings or legacy compatibility. A line such as Interior.ColorIndex = 3 refers to an indexed color, not “RGB value 3.” That makes it less descriptive and less dependable when you need a precise modern color.
Some VBA constants are convenient for standard colors. For example, vbRed, vbBlue, and vbGreen can be assigned to a compatible color property. They are useful for simple code, but their basic colors may not match a company palette or a carefully chosen shade. For branded or accessible color schemes, use explicit RGB values or workbook theme colors instead.
- Use
RGBwhen you need a specific, custom shade. - Use a theme color when the formatting should follow the workbook’s theme.
- Use
ColorIndexonly when working with a legacy workbook or code that specifically depends on its palette. - Use a named VBA color constant for simple, familiar colors when exact shade matching is not important.
Theme colors and tints
Excel themes let a workbook use coordinated colors that can change together when the theme changes. VBA can refer to a theme slot through properties such as ThemeColor on a fill, and can apply a lighter or darker variation with TintAndShade. This approach can be more flexible than hard-coding RGB values when a workbook is designed to support multiple themes.
Theme colors are not interchangeable with RGB values or ColorIndex numbers. A theme color identifies a position in the workbook’s theme palette; its displayed color depends on the theme. If the workbook uses a different theme later, the appearance can change while the formatting remains linked to that theme slot. Conversely, a fixed RGB color stays the same when the theme changes. Choose based on whether the workbook should follow its theme or preserve a particular color exactly.
When applying theme-based formatting, use the object model’s theme properties for the relevant fill or font and check the result in the actual workbook. A numeric RGB assignment is simpler for a fixed shade, while theme properties require you to select the intended theme slot and, if needed, a tint. This distinction is especially useful when a macro must match existing theme-based formatting.
Find or inspect a color already in a workbook
If you need to reproduce an existing fill, select the cell in Excel and inspect its color in the VBA editor’s Immediate Window. Open the editor, then press Ctrl+G on Windows to display the Immediate Window. For example, type ?Worksheets("Sheet1").Range("A1").Interior.Color and press Enter to see the numeric color value. The question mark is shorthand for printing an expression’s result in that window. On Mac, use the editor’s Immediate Window; the shortcut may differ by keyboard configuration.
The returned number is a VBA color value, not a hexadecimal string formatted as #RRGGBB. To reproduce the color, the simplest dependable approach is often to copy the existing cell’s formatting or to inspect and record the RGB channels using Excel’s color controls. If the cell is colored by conditional formatting, its displayed color may not be the same as its underlying Interior.Color. Inspect the conditional formatting rule as well as the cell’s direct formatting.
For manually entering an RGB color in Excel, use the color picker’s custom color controls where available and note the red, green, and blue values. Then use those same channel values in VBA. This avoids confusing the VBA Long integer with a hex code copied from a design tool or website.
Common problems and how to avoid them
- Using the wrong property:
Interior.Colorchanges the fill, whileFont.Colorchanges text. Confirm which part of the cell should change. - Reversing RGB channels:
RGBtakes red first, green second, and blue third. A blue-and-red swap can produce a very different color. - Entering a hex string as a number: A value such as
#2E75B6is not a valid direct replacement forRGB(46, 117, 182). - Expecting Ctrl+Z to undo a macro: Excel clears its normal undo history when VBA runs. Save a separate copy before running code that changes formatting or data.
- Not seeing the expected fill: Conditional formatting, table styles, or another formatting rule can affect what appears. Check those features before assuming the VBA assignment failed.
- Using an unsupported environment: VBA macros do not run in Excel for the web. Open the workbook in the desktop Excel application to run them.
For repeatable automation, keep color values in one clearly named location or use constants rather than scattering unexplained numbers throughout a long macro. That makes it easier to update a palette and reduces the chance that two procedures use slightly different shades by mistake. Test on a copy, especially if the macro formats a large range or is part of an automated workflow.
When to use conditional formatting instead
VBA is appropriate when a macro is already part of a process, when formatting must be applied during an import or report-building step, or when the color choice involves custom logic that is difficult to express with a rule. However, VBA writes formatting at the time the macro runs. If a cell’s value changes afterward, its fill will not necessarily update unless the macro runs again.
For a color that should respond immediately to changing values, use Excel’s conditional formatting. On Windows, select the range and choose Home > Conditional Formatting, then select a suitable rule or create one with New Rule. For example, a rule can highlight cells that contain a particular status. Conditional formatting is also useful because it separates the visual rule from the data and can be edited through Excel’s interface. It can override the appearance of direct formatting, which is why a VBA-assigned fill may not look like the displayed result.
Conditional formatting is not a replacement for every macro. A macro can apply a chosen format as part of a larger procedure, work with workbook objects, or make decisions that involve several conditions. The practical question is whether the color should be a lasting formatting change or a live visual response to the cell’s current value.
Frequently Asked Questions
What is the VBA code for red?
For a red fill, use Range("A1").Interior.Color = RGB(255, 0, 0). Replace A1 with the cell or range you want to format. Use Font.Color instead if you want red text.
How do I use a hex color code in Excel VBA?
Convert the hexadecimal pairs into decimal red, green, and blue channel values, then pass them to RGB. For example, #2E75B6 is RGB(46, 117, 182). The hex text itself should not be assigned directly to .Color.
What is the difference between Color and ColorIndex?Color represents a direct color value, commonly supplied through RGB. ColorIndex points to a position in an indexed palette and is mainly relevant to older or palette-dependent workbooks. They are different systems and their numbers should not be treated as equivalent.
Why does my VBA fill color not appear?
Check that the code targets the right worksheet and range and uses Interior.Color for the fill. Conditional formatting or a table style may affect the visible result. Also confirm that the macro ran in desktop Excel, since Excel for the web does not run VBA.
Can I undo a VBA color change with Ctrl+Z?
No. Running VBA generally clears Excel’s normal undo history, so Ctrl+Z cannot reverse the macro’s changes. Save a copy of the workbook before running a macro that changes formatting, or write the macro so it can deliberately restore prior formatting.
Related
- Excel Custom Number Format for Millions
- Excel Custom Number Format: Show Numbers in Thousands
- Excel Shortcut to Select the Rest of a Column Down
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Excel VBA Get Username: Windows or Excel User Name?In Excel VBA on Windows, use Environ$("USERNAME") to read the current Windows account name. Use Application.UserName instead if…
- Running Macros in Google Sheets: How to Run and Manage ThemTo run a macro in Google Sheets, open the spreadsheet in a web browser, choose Extensions > Macros,…
- Excel VBA Date Difference: Calculate Days and MonthsIn Excel VBA, use DateDiff to count calendar boundaries between two dates, for example DateDiff("d", startDate, endDate) for…
- Word VBA Mail Merge: How to Automate ItWord VBA can automate a mail merge by telling a prepared Word merge document to create a new…
- Razor Macro Recorder for UO: Setup, Limits and TipsYes. Razor for Ultima Online includes a macro recorder in many classic releases: open its Macros tab, create…
- VBA Function Return String: Syntax and ExamplesYes. A VBA function returns a string when its declaration ends in As String; inside the function, assign…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.