将单元格中文本的值和颜色传递给用户定义的函数



目前,我在将单元格的值及其各自的文本颜色传递给我的用户定义函数时遇到问题。我将引用作为范围传递并使用.Font.ColorIndex。然后在 IF 语句中使用它来确定是否有任何红色(值为 3(,然后使用 application.caller.fontIndex=3 将单元格文本变为红色。

Public Function Example(AA As Range, BB As Range) As double
Dim AAcolor, BBcolor As Integer
AAcolor=AA.font.colorindex
BBcolor=BB.font.colorindex
IF BBcolor=3 Or AAcolor=3 Then
Application.caller.font.colorIndex=3
End If 

代码的其余部分只是从输入的范围计算双精度的公式,该范围以双精度返回。

为了澄清,我正在尝试确定引用的输入单元格的文本颜色。如果我可以从我的 UDF 调用 sub,我不仅限于 UDF 来执行此操作。

概念证明...

试试这个...使用 F5 或 F8 逐步完成"sub abc123"并在工作表上观看 K5(I5 只是为 UDF 提供一个变量(

它来自录制的宏,所以有点复杂

注意:如果您想做更多事情,请在另一个单元格中使用另一个 UDF

Sub abc123()
' run on empty worksheet
Rows("5:5").Delete
Range("K5").FormulaR1C1 = "56.7"                                         ' just some random data
Range("K5").FormatConditions.Add Type:=xlExpression, Formula1:="=J5=3"   ' conditional format dependent on value of J5
Range("K5").FormatConditions(Range("K5").FormatConditions.Count).SetFirstPriority
Range("K5").FormatConditions(1).Font.Color = -16776961
Range("K5").FormatConditions(1).Font.TintAndShade = 0
Range("K5").FormatConditions(1).StopIfTrue = False
Range("J5").FormulaR1C1 = "=example(RC[-1])" ' UDF returns value to J5
Stop
Range("I5").FormulaR1C1 = "2"                ' just some values passed to UDF
Stop
Range("I5").FormulaR1C1 = "3"                ' this one should make K5 go red
Stop
Range("I5").FormulaR1C1 = "4"
End Sub

Public Function Example(a As Variant) As Variant     ' UDF
Example = a                                      ' just echo back the value that was received
End Function

相关内容

最新更新