简体   繁体   中英

Excel+VBA How can I set the bg colour of a cell using its own contents?

I'm trying to get a sheet where entering an RGB value into a cell will set the background colour to that value. I know I can use

Range("A1:BE57").Interior.Color = RGB(127, 255, 127)

to set the background for the whole range to any one colour, but I would like each individual cell in that range to pull from its own contents.

ideally just having

Range("A1:BE57").Interior.Color = RGB(.Value)

where .Value would be replaced with the actual contents of the cell (ie 127, 255, 127) for each instance in the range. Though i'm aware it is unlikely to be that simple.

is this possible?

Ok. Here is a VBA function that takes a string and attempts to turn it into a VBA Color-compatible string. Below is an extremely simple usage example. You should be able to take this function and add it to your code base. There is no input validation to ensure that the RGB string is in correct format but I have tried it with your original value of "127, 255, 127" and it works as well as "'127,255,127" as a value in A1. Hopefully this is clear for you now.

' Converts a RGB string value to a HEX string you can use to set Color properties
' Splits the string into RGB values, reverses them for VBA, and returns a HEX string
Public Function ConvertValueToColour(rgbString As String) As String

' Define an array to hold the RGB values
Dim Colors() As String

' Initialize the return string
ConvertValueToColour = "&H"

' Split the input
Colors() = Split(rgbString, ",")

' Loop in reverse for VBA (Likes GBR not RGB)
For i = UBound(Colors()) To LBound(Colors()) Step -1
    ConvertValueToColour = ConvertValueToColour & Hex(RTrim(LTrim(Colors(i))))
Next i

End Function

' This Sub calls the above function
Public Sub ColorA1()
Range("A1").Interior.color = ConvertValueToColour(Range("A1").Value)
End Sub

*Note I have rewritten the function so removed the credit to MrExcel

First of all you cannot invoke function RGB like that:

RGB(.Value)

because it requires three parameters of Integer type.


Furthermore, I don't think it is possible to do it with a single line. I am afraid you need to iterate through all the cells in your range.

If you store the values of RGB in cells in such format 100;100;100 , you could use the code below:

Sub setBackground()
    Dim cell As Excel.Range
    Dim colors() As String
    '--------------------------------------------------------------------------

    For Each cell In Range("A1:BE57").Cells
        colors = VBA.Split(cell.value, ";")
        cell.Interior.Color = RGB(CInt(colors(0)), CInt(colors(1)), CInt(colors(2)))
    Next cell
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM