Excel + VBA如何使用自己的内容设置单元格的颜色?

我试图得到一个工作表,在一个单元格中input一个RGB值将背景颜色设置为该值。 我知道我可以使用

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

将整个范围的背景设置为任何一种颜色,但是我希望在该范围内的每个单独的单元从其内容中拉出。

最好只是有

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

其中.Value将被replace为该范围中的每个实例的单元的实际内容(即127,255,127)。 虽然我知道这不太可能是那么简单。

这可能吗?

好。 这是一个VBA函数,它接受一个string并尝试将其转换为VBA颜色兼容的string。 以下是一个非常简单的使用示例。 你应该可以把这个函数添加到你的代码库中。 没有inputvalidation,以确保RGBstring是正确的格式,但我已经尝试与您的原始值“127,255,127”,它的作品,以及“127,255,127”作为一个值在A1。 希望你现在明白这一点。

 ' 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 

*注意我已经重写了这个函数,所以删除了MrExcel的功劳

首先你不能像这样调用RGB函数:

 RGB(.Value) 

因为它需要三个Integertypes的参数。


而且,我认为不可能只用一行。 恐怕你需要迭代你的范围内的所有单元格。

如果以100; 100; 100的格式将RGB的值存储在单元中,则可以使用以下代码:

 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