To set an Excel cell’s fill color from a hex value such as #1E90FF, convert its red, green, and blue pairs to VBA’s RGB function and assign the result to Range("A1").Interior.Color. For example, RGB(30, 144, 255) produces that blue fill; reusable conversion code appears below.
What Excel means by a hex color
Hex color codes commonly use the format #RRGGBB: the first two digits represent red, the next two green, and the last two blue. Each pair is a hexadecimal number from 00 to FF, equivalent to a decimal value from 0 to 255. The leading # is a familiar marker in HTML and design tools, but it is not part of the three color components.
Excel’s VBA color properties use a numeric Long, not a text string such as "#1E90FF". VBA’s built-in RGB(red, green, blue) function accepts the three decimal components and returns the number Excel expects. For #1E90FF, those components are 30, 144, and 255, so the equivalent expression is RGB(30, 144, 255).
This is why assigning the text directly does not work: Excel needs a color value, not a six-character label. Also, do not simply interpret the entire text 1E90FF as one number and assign it. Excel’s internal numeric color representation does not follow the visual left-to-right order of an #RRGGBB string. Converting each pair and passing the components to RGB avoids that order trap.
Set one cell to a known color
If the color is fixed and you already know its red, green, and blue values, a short macro is enough. In Excel for Microsoft 365 on Windows, press Alt+F11 to open the Visual Basic Editor, choose Insert > Module, and paste this procedure into the module:
Sub ColorOneCell()
' Set A1 to the color #1E90FF.
Range("A1").Interior.Color = RGB(30, 144, 255)
End Sub
Run the macro from the Visual Basic Editor or from Excel’s Developer tab. The Interior object refers to a cell’s fill formatting, while its Color property receives the color value. To color a different cell, replace A1 with a valid cell reference, such as B3 or Sheet1!A1. Qualifying the worksheet is helpful when a macro could run while another sheet is active.
On a Mac, the VBA editor is also available, typically through Developer > Visual Basic; keyboard shortcuts can vary with the keyboard and macOS settings. The basic RGB and Interior.Color code works in desktop Excel for Mac as well. Excel for the web does not run VBA macros, so use desktop Excel to execute this code.
Convert a #RRGGBB string with a reusable function
When the color comes from a design specification, a cell, or a list of hex codes, a small conversion function is more convenient than manually calculating each component. This version accepts six hexadecimal digits with or without a leading #, ignores surrounding spaces, and reports an error for malformed input.
Function HexToColor(ByVal hexColor As String) As Long
Dim i As Long
Dim digits As String
' Allow either RRGGBB or #RRGGBB, with surrounding spaces.
digits = Trim$(hexColor)
If Left$(digits, 1) = "#" Then digits = Mid$(digits, 2)
If Len(digits) <> 6 Then
Err.Raise vbObjectError + 1000, "HexToColor", _
"Enter six hexadecimal digits, optionally preceded by #."
End If
' Reject characters outside 0-9 and A-F.
For i = 1 To 6
If InStr(1, "0123456789ABCDEF", Mid$(digits, i, 1), vbTextCompare) = 0 Then
Err.Raise vbObjectError + 1001, "HexToColor", _
"The color contains a non-hexadecimal character."
End If
Next i
' Convert the RR, GG, and BB pairs to decimal components.
HexToColor = RGB(CLng("&H" & Mid$(digits, 1, 2)), _
CLng("&H" & Mid$(digits, 3, 2)), _
CLng("&H" & Mid$(digits, 5, 2)))
End Function
Sub ApplyHexColor()
' Apply #1E90FF to A1.
Range("A1").Interior.Color = HexToColor("#1E90FF")
End Sub
The function validates the input before converting it, so a typo is reported rather than silently treated as a different color. The CLng("&H" ...) expressions interpret each two-character pair as hexadecimal; RGB then assembles the three decimal components in the form Excel uses. Keep the function and the procedure in the same standard module, or make the function available in the module where the calling macro can use it.
Before running any macro, save a copy of the workbook. VBA changes to formatting cannot be reversed with Ctrl+Z in Windows Excel; on Mac, Command+Z is the usual undo shortcut, but it does not make a macro’s changes undoable either. Save macro-enabled workbooks as .xlsm if you need to retain VBA code.
Apply a hex color to a range or a list
The same conversion works with a range rather than a single cell. To fill a block uniformly, assign the color to the block’s Interior.Color property. For a different hex value on each row, loop through the rows and read the corresponding text value from another column. For example, with hex codes in B2:B10 and cells to color in A2:A10, add this procedure alongside HexToColor:
Sub ColorRowsFromHexList()
Dim ws As Worksheet
Dim rowNumber As Long
Dim hexValue As String
Set ws = ThisWorkbook.Worksheets("Sheet1")
For rowNumber = 2 To 10
hexValue = CStr(ws.Cells(rowNumber, "B").Value2)
ws.Cells(rowNumber, "A").Interior.Color = HexToColor(hexValue)
Next rowNumber
End Sub
This example expects each B-cell to contain a valid six-digit code, optionally starting with #. A blank cell or invalid code raises the validation error, which is usually preferable to applying an unintended color. If the list has a variable length, determine the last used row in column B before looping and handle a blank list separately. Always qualify references with a worksheet, as in this example, when the macro should not depend on whichever sheet happens to be active.
Fill color, font color, and other color properties
Use the property that corresponds to the part of the cell you want to format. Interior.Color changes the cell’s fill; Font.Color changes the text color. For example, the following assignment makes the text in A1 blue without changing its fill:
Sub SetFontColor()
' Set the font color in A1 to #1E90FF.
Range("A1").Font.Color = RGB(30, 144, 255)
End Sub
For a fill, you can set the pattern explicitly when you want a solid background: Range("A1").Interior.Pattern = xlSolid. This can help make the intended formatting clear in code. Borders have their own color properties, such as a border’s Color; changing the cell’s Interior.Color does not color its outline.
Do not confuse Color with ColorIndex. Color accepts the RGB color value and is the straightforward choice for a precise hex color. ColorIndex refers to an indexed palette, a legacy approach that may not match a requested modern RGB color. If exact color matching matters, convert the hex code and use Color.
Theme colors and conditional formatting
An explicit RGB color and a theme color behave differently. A direct assignment such as Interior.Color = HexToColor("#1E90FF") specifies a particular RGB fill. A theme-based fill is associated with the workbook’s theme and may change if that theme changes. Use the RGB method when the requested hex value must remain the same; consider theme colors when the workbook should adapt to a shared visual theme.
Conditional formatting is another important distinction. A rule can determine the visible fill based on a cell’s value, and its formatting may take precedence over the ordinary fill you set with Interior.Color. If a macro appears to run but the displayed color does not change as expected, inspect the range’s rules through Home > Conditional Formatting > Manage Rules. Decide whether the color should be fixed by VBA or controlled by the rule, rather than having both compete for the appearance.
To read the color that is currently displayed because of conditional formatting, VBA offers DisplayFormat in supported desktop Excel versions. That is for reading the displayed result; it is not a replacement for assigning a normal fill through Interior.Color. For a rule-based color, edit the conditional formatting rule itself.
Common errors and how to avoid them
- The color looks wrong: Check that the input is in
RRGGBBorder and that the red, green, and blue pairs are passed separately toRGB. Do not reverse the pairs or assign the six-digit text as one decimal number. - The macro reports a type or conversion error: Confirm the string has exactly six hex digits after an optional
#. Characters outside 0–9 and A–F, hidden spaces inside the code, and shorthand three-digit codes such as#ABCare not accepted by the function above. - The fill does not appear to change: Verify the intended worksheet and cell, look for conditional formatting, and check whether the cell is part of a merged range. A macro that uses an unqualified
Range("A1")acts on the active sheet, which may not be the sheet you intended. - The macro is unavailable: Excel for the web cannot execute VBA. In desktop Excel, save the file in a macro-enabled format when retaining code and use a trusted source for macros; do not lower macro security to run unknown files.
- Undo does not restore the old fill: VBA macro actions generally clear Excel’s undo history. Use a saved copy or add code that records the old formatting if your workflow needs a deliberate way to restore it.
Alternatives when VBA is not the right tool
If the color is a one-time choice, use Excel’s fill color controls instead of creating a macro. On Windows, select the cells and use Home > Fill Color; the More Colors option lets you enter RGB values. The exact dialog wording and available color-entry controls can vary between Windows and Mac versions, so use the desktop interface available in your installation. This approach avoids code but is less convenient for repeatedly applying a long list of hex codes.
For formatting that should respond to cell values, conditional formatting is usually more suitable than a macro that must be rerun after data changes. For automation that must run in Excel for the web, VBA is not available there; Office Scripts are a separate automation option in supported Microsoft 365 environments. They use a different programming model, so VBA code cannot simply be pasted into an Office Script.
Frequently Asked Questions
Can I use a hex string directly in Interior.Color?
No. Interior.Color expects a numeric color value. Convert the three pairs in the hex string to red, green, and blue values and pass them to RGB, or use a function such as HexToColor.
Does the hex code need the # sign?
No. The conversion function above accepts both #1E90FF and 1E90FF. It trims spaces at the beginning and end, but still requires six valid hexadecimal digits after the optional marker.
How do I set a cell’s font color instead of its fill?
Use Range("A1").Font.Color = HexToColor("#1E90FF"). Use Interior.Color for the fill and Font.Color for the text; these are separate formatting properties.
Why does the fill color not change when the macro runs?
Check that the macro targets the correct sheet and range, and inspect conditional formatting rules that may control the visible result. Also confirm that you are running the macro in desktop Excel, not Excel for the web.
Can I run this VBA in Excel for the web?
No. Excel for the web does not run VBA macros. Open the workbook in desktop Excel for Windows or Mac to use VBA, or consider Office Scripts in an environment where they are supported.
Related
- Excel Shortcut to Select the Active Cell’s Entire Column
- Excel Shortcut to Select to the Bottom of a Column
- Excel Shortcut to Select All Rows in a Column at Once
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Convert Excel Macros to Google Sheets: What Works?Yes, you can move an Excel macro workflow to Google Sheets, but you generally cannot run its VBA…
- VBA UserForm: How to Show It in ExcelTo show a VBA UserForm in Excel, call its name followed by .Show, such as UserForm1.Show. Add vbModeless…
- MS Access VBA: Send Email With an Attachment SafelyYes. In Microsoft Access for Windows, VBA can create an email in classic Outlook, add a file with…
- VBA ArrayList: How to Create and Use It in Excel VBAIn VBA, an ArrayList is a resizable, zero-based list that you can create on Windows with CreateObject("System.Collections.ArrayList"). It…
- Excel VBA: Open a File Dialog to Select a FolderTo let someone choose a folder in Excel VBA, use Application.FileDialog(msoFileDialogFolderPicker). Show the dialog, check whether the user…
- Excel VBA Compile Error: Next Without For ExplainedIn Excel VBA, “Next without For” means VBA found a Next statement that it could not match to…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.