How to update the Cell color in Excel

I am working on a project where I need to update the cell colors in an Excel spreadsheet based on the cell values dynamically.

Dynamic Cell Color Update: I need to change the color of cells based on their values.

For example, if a cell contains the value “Important,” it should be highlighted in red.

Any help or guidance would be greatly appreciated!

That is not possible without you setting up conditional formatting to begin with.
There are many guides out here on how to do that, here is one.

1 Like

I guess it depends on what you call dynamic.
If you want a truly dynamic solution, then conditional formatting is the way to go.

But, it you’re constructing the Excel from scratch, that’s not always an option.
You can do it programmatically from OpenRPA, but it’s not going to be super fast for large files.

Something like this works (remember to closeworkbook with save=true in finally, otherwise you won’t see any changes)

The “just to get wb” is a read cell, we need to fetch the Workbook reference from it (unless you already have it from somewhere else).
Then in InvokeCode:

Dim worksheet = wb.Sheets(sheetName)
Dim cell = worksheet.Cells(2,4)
If (cell.Text = "Important") Then
  worksheet.Cells(2,4).Interior.Color = Microsoft.Office.Interop.Excel.XlRgbColor.rgbRed
  Else
  worksheet.Cells(2,4).Interior.Color = Microsoft.Office.Interop.Excel.XlRgbColor.rgbGreen
End If

How to iterate throughout the cells is left as an exercise to the reader :wink:

4 Likes

lol, that’s cheating @AndrewK … but yeah, nicely done … you are right … that would work too.

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.