【发布时间】:2012-11-22 05:48:09
【问题描述】:
我在 Excel 中有一个用户定义的函数。它被称为电子表格单元格中的公式函数并且工作正常。
我希望函数能够根据返回的值更改单元格的颜色。本质上,改变单元格的颜色是函数的副作用。
我试过了
Application.ThisCell.Interior.ColorIndex = 2
但它失败了。
【问题讨论】:
我在 Excel 中有一个用户定义的函数。它被称为电子表格单元格中的公式函数并且工作正常。
我希望函数能够根据返回的值更改单元格的颜色。本质上,改变单元格的颜色是函数的副作用。
我试过了
Application.ThisCell.Interior.ColorIndex = 2
但它失败了。
【问题讨论】:
这里演示了 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
【讨论】:
这是无法做到的。用户定义的函数不能改变工作簿/工作表等的状态。
使用条件格式来实现您的目标。
编辑:这更像是一个建议,而不是真正的答案。
【讨论】:
不,您不能使用 Function() 更改单元格的颜色。但是,您可以在 Sub() 例程中更改它。
只需编写一个 Sub(),它将在您希望在其上运行的单元格上运行您的函数,然后在每个单元格运行后,放置一个 If 语句以查看您是否要根据它返回的值对其进行着色.
【讨论】:
您可以创建一个在工作表发生更改后自动运行的 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
【讨论】:
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
【讨论】:
Evaluate?真的吗?
我尝试了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
【讨论】: