繁体   English   中英

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

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

我正在尝试获取一个表格,在单元格中输入RGB值会将背景颜色设置为该值。 我知道我可以使用

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

将整个范围的背景设置为任何一种颜色,但我希望该范围内的每个单元格都可以从其自己的内容中提取。

理想的只是拥有

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

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

这可能吗?

好。 这是一个VBA函数,它接受一个字符串并尝试将其转换为与VBA颜色兼容的字符串。 下面是一个非常简单的用法示例。 您应该能够使用此功能并将其添加到您的代码库中。 没有输入验证来确保RGB字符串的格式正确但我已经尝试使用原始值“127,255,127”,并且它与A1中的值“127,255,127”一样有效。 希望现在这对你来说很清楚。

' 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)

因为它需要三个Integer类型的参数。


此外,我认为不可能用一条线来做。 我担心你需要遍历你范围内的所有细胞。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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