Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.5k views
in Technique[技术] by (71.8m points)

excel - Assign cell color function

trying to create a function that colour a cells interior (using RGB) according to user input and coded below, can't understand why this is not working though, can anyone advise,

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A possible workaround to the inability to call directly is to load relevant data into a global variable/type then use a caller function (in this case SheetCalculate) to fire the event you want. For eg.

ThisWorkbook Code

Private Sub Workbook_SheetCalculate(ByVal Sh As Object)
    Call ColorRGB
End Sub

Module Code

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

Please note that if you delete the function from the sheet though, no update is performed


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...