分配单元格颜色功能

时间:2021-01-12 16:32:56

标签: excel vba

试图创建一个函数,根据用户输入和下面的编码为单元格内部着色(使用 RGB),但无法理解为什么这不起作用,任何人都可以提出建议,

Function RGBC(r, g, b)

Dim src As Range

Set src = Application.ThisCell

With src
.Interior.Color = RGB(r, g, b)
End With
 
End Function

1 个答案:

答案 0 :(得分:0)

无法直接调用的一种可能解决方法是将相关数据加载到全局变量/类型中,然后使用调用函数(在本例中为 SheetCalculate)来触发您想要的事件。例如。

<块引用>

本工作簿代码

Private Sub Workbook_SheetCalculate(ByVal Sh As Object)
    Call ColorRGB
End Sub
<块引用>

模块代码

Private Type RangeRGB
    Update As Boolean
    WS As String
    RNG As String
    RGBColor As Long
End Type

Private tRGB As RangeRGB

Public Function RGBColor(R As Long, G As Long, B As Long)
    On Error GoTo ExitFunction
    tRGB.RNG = Application.Caller.Address
    tRGB.WS = Application.Caller.Worksheet.Name
    tRGB.RGBColor = RGB(R, G, B)
    tRGB.Update = True
ExitFunction:
End Function

Function ColorRGB()
    On Error GoTo ExitFunction
    If tRGB.Update = True Then
        With Worksheets(tRGB.WS)
            Range(tRGB.RNG).Interior.Color = tRGB.RGBColor
        End With
        tRGB.WS = ""
        tRGB.RNG = ""
        tRGB.Update = False
    End If
ExitFunction:
End Function

请注意,如果您从工作表中删除该功能,则不会执行任何更新

相关问题