从自定义公式更改单元格的背景颜色

时间:2017-01-30 15:45:49

标签: excel vba excel-vba

我创建了一个看起来像这样的公式函数

Function CalculateCPOTracker(Model As String, Mcodes As String, Opt As String, RegionId As String, RecTotalAvailNFormat As String, RecTotalAvailValue As String, GroupModel As String, MandateFormat As String, MandateValue As String, RowNumber As String) As Double
.....
CalculateCPOTracker = buffer

End Function

在此功能的最后,我需要更改单元格的背景颜色。我试图做这样的事情

Worksheets("Rec").Range("BA:BA").Rows(38).Interior.Color = RGB(255, 255, 0)

但它对我不起作用。它会停止正确计算。 这可以通过公式函数来实现吗?

1 个答案:

答案 0 :(得分:1)

试试这样:

Worksheets("Rec").cells(52,38).interior.color = rgb(255,255,0)

但是在VBA中更改字体不是一个好习惯。通常函数应该返回值,并且更改应该由sub完成。像这样:

Public sub ChangeColor (rngCell as range)
    rngCell.interior.color = rgb(255,255,0)
end sub

即使有颜色的可选值:

Option Explicit

Public Sub ChangeColor(rngCell As Range, _
                        Optional lngR As Long = 255, _
                        Optional lngG As Long = 255, _
                        Optional lngB As Long = 0)

    rngCell.Interior.Color = RGB(lngR, lngG, lngB)

End Sub

编辑: 实际上,这取决于你想要做什么: 如果要将该函数用作工作表函数,则无法更改颜色,如@Scott Craner在注释中所述。但是,如果从VBA运行该功能,则可以执行此操作。试试这个小例子来看看差异:

Option Explicit

Public Function ColorAndBy10(rngMyRange As Range) As Long

    rngMyRange.Interior.Color = vbRed
    ColorAndBy10 = 10 * rngMyRange.Value

End Function


Public Sub TestMe()

    Range("b1").Formula = "=ColorAndBy10(A1)"
    Range("b2") = ColorAndBy10(Range("a2"))

End Sub


Public Sub TestMe()

    Range("b1").Formula = "=ColorAndBy10(A1)"
    Range("b2") = ColorAndBy10(Range("a2"))

End Sub