2

我在 Excel 中有一个用户定义的函数。它被称为电子表格单元格中的公式函数并且工作正常。

我希望该函数能够根据返回的值更改单元格的颜色。本质上,改变单元格的颜色是函数的副作用。

我试过了

Application.ThisCell.Interior.ColorIndex = 2

但它失败了。

4

6 回答 6

11

下面演示了 VBA UDF 如何更改工作表内容的颜色,而不是使用条件格式。

只要两个工作表的行和列都按相同的顺序排序,那么这将比较两个单独的 Excel 工作表之间每个单元格的差异。

您可以将其添加到第三张纸上所需的任意数量的单元格中,以检测两张纸上相同两个单元格之间的差异,其中包含以下数据:=DifferenceTest(Sheet1!A1,Sheet2!A1)

而要存储在VBA编辑器中的函数如下:

Function DifferenceTest(str1 As String, str2 As String) As String

    If str1 = str2 Then
            Application.Caller.Font.ColorIndex = 2
    Else
            Application.Caller.Font.ColorIndex = 3
            DifferenceTest = str1 & " vs " & str2
    End If

End Function
于 2015-06-26T13:54:39.397 回答
9

这是无法做到的。用户定义的函数不能改变工作簿/工作表等的状态。

使用条件格式来实现您正在尝试的内容。

编辑:这更多是一个建议,而不是一个真正的答案。

于 2012-12-04T15:05:30.483 回答
1

不,您不能使用Function()更改单元格的颜色。但是,您可以在Sub()例程中更改它。

只需编写一个 Sub(),它将在您希望在其上运行的单元格上运行您的函数,然后在每个单元格运行后,放置一个 If 语句以查看是否要根据它返回的值对其进行着色。

于 2012-12-05T07:28:19.200 回答
1

您可以创建一个在工作表发生更改后自动运行的 vba 代码。而不是将代码放在单独的模块中,您必须将其嵌入工作表本身。

右键单击工作表选项卡,选择查看代码,然后创建以下代码:

Private Sub Worksheet_Change(ByVal Target As Range)

For Each cell In Range("A1:B8") 'change cell range as needed

Select Case cell.Value
Case 8
cell.Interior.ColorIndex = 4 'cell color becomes green when cell value is 8
Case ""
cell.Interior.ColorIndex = 1 'cell color becomes black when cell is empty
Case Is < 6
cell.Interior.ColorIndex = 7 'cell color becomes pink when cell value is smaller than 6
Case Else
cell.Interior.ColorIndex = 0 'all other cells get no color
End Select

Next cell

End Sub
于 2013-05-16T13:21:09.927 回答
0
Function HexToLongRGB(sHexVal As String) As Long
    Dim lRed As Long
    Dim lGreen As Long
    Dim lBlue As Long
    lRed = CLng("&H" & Left$(sHexVal, 2))
    lGreen = CLng("&H" & Mid$(sHexVal, 3, 2))
    lBlue = CLng("&H" & Right$(sHexVal, 2))
    HexToLongRGB = RGB(lRed, lGreen, lBlue)
End Function

Function setBgColor(ByVal stringHex As String)
    Evaluate "setColor(" & Application.Caller.Offset(0, 0).Address(False, False) & ",""" & stringHex & """)"
    setBgColor = ""
End Function

Sub setColor(vCell As Range, vHex As String)
    vCell.Interior.Color = HexToLongRGB(vHex)
End Sub
于 2017-08-27T03:43:19.897 回答
0

我尝试了该Evaluate方法,该方法有效但立即崩溃(2007 年)。帮助提到缓存地址,所以这是我的方法 - 将单元格和颜色存储在集合中,然后在计算后更改颜色。

Dim colorCells As New Collection

Function UDF...
    UDF = <whatever>
    color = <color for whatever>
    colorCells.Add (Application.Caller)
    colorCells.Add (color)
End Function

Sub SetColor()
    While colorCells.Count <> 0
        colorCells(1).Interior.Color = colorCells(2)
        colorCells.Remove (1)
        colorCells.Remove (1)
    Wend
End Sub

Private Sub Workbook_SheetCalculate(ByVal Sh As Object)
    SetColor
End Sub
于 2018-09-24T01:41:56.043 回答