3
votes

Below is a screenshot of what I hope to achieve in a way other than manually copying and pasting.

It's the material design color pallet and it looks great in Excel.

How can I loop through range B2:B15 and set each cell background color to its corresponding containing color?

Perhaps a VBA loop to go through the vertical B range of cells, parsing each cell content, and setting the cell background-color to the RGB value that the cell contains.

So a RED-50 cell containing rgb(255, 235, 238) becomes...

Range("B2").Interior.Color = RGB(255, 235, 238)

image1


UPDATE!

Thank you everyone for the help. Below is the google drive link to the Excel material design palette you've help me build.

Press Control + M to activate.

material.design.colors.xlsm

So ALL COLORS become themselves.

image2

3

3 Answers

2
votes

Perhaps something like that? I couldn't pass the cell's value into Interior.Color so I decided to use Split to extract each color individually. Adjust Sheet1 if needed.

Sub InteriorColor()
    Dim rngCell As Excel.Range
    Dim varColors As Variant
    Dim lngR As Long, lngG As Long, lngB As Long

    For Each rngCell In Sheet1.Range("B2:B15")
        varColors = Split(rngCell.Value, ",")
        lngR = Right(varColors(0), Len(varColors(0)) - 4)
        lngG = Trim(varColors(1))
        lngB = Left(varColors(2), Len(varColors(2)) - 1)

        rngCell.Interior.Color = RGB(lngR, lngG, lngB)
    Next rngCell
End Sub

Result:

enter image description here

2
votes

A simple solution without resorting to regex:

Sub test()
    Dim r As Range
    For Each r In Range("B1:B10")
        r.Interior.Color = StringToRGB(r.Text)
    Next
End Sub

Public Function StringToRGB(s As String) As Long
    Dim parts
    s = Mid(s, 5, Len(s) - 5)
    s = Replace(s, " ", "")
    parts = Split(s, ",")
    StringToRGB = RGB(CInt(parts(0)), CInt(parts(1)), CInt(parts(2)))
End Function
1
votes

This splits the contents in parentheses into three elements in a variant array and uses the RGB function to apply them to the cells. You will want to add some error checking to make sure the cell contain valid RGB values.

Sub ApplyColor()
Dim cell As Excel.Range
Dim RGBs As Variant

For Each cell In ActiveSheet.Range("B2:B15")
   RGBs = Split(Replace(Replace(cell.Value, "rgb(", ""), ")", ""), ",")
   cell.Interior.Color = RGB(RGBs(0), RGBs(1), RGBs(2))
Next cell
End Sub