我编写了一个功能,通过将值1和2分配给不同的条件格式化单元格,实质上返回加权分数。当我在工作表中调用此函数时,它返回#VALUE!错误。
Function ColorWeight(Factors As Range) As Integer
Dim x As Range
Dim score As Integer
score = 0
For Each x In Factors
If x.DisplayFormat.Interior.color = Range("C5").Interior.color Then
score = score + Cells(14, x.Column).Value * 2
ElseIf x.DisplayFormat.Interior.color = Range("C9").Interior.color Then
score = score + Cells(14, x.Column).Value * 1
End If
Next
ColorWeight = score
End Function
但是,当我将此代码作为子程序运行并将范围设置为特定范围时,如下所示,它可以正常工作。
Sub ColorWeight()
Dim Factors As Range
Dim x As Range
Dim score As Integer
Set Factors = Range("G17:Q17")
score = 0
For Each x In Factors
If x.DisplayFormat.Interior.color = Range("C5").Interior.color Then
score = score + Cells(14, x.Column).Value * 2
ElseIf x.DisplayFormat.Interior.color = Range("C9").Interior.color Then
score = score + Cells(14, x.Column).Value * 1
End If
Next
Debug.Print score
End Sub
我错过了哪些让这个功能不起作用的区别?
答案 0 :(得分:3)
以下是解决方法的基本示例:
Function GetDFColor(shtName, cellAddress)
GetDFColor = ThisWorkbook.Sheets(shtName).Range(cellAddress). _
DisplayFormat.Interior.Color
End Function
'works when called as a UDF
Function DisplayFormatColor(rng As Range)
DisplayFormatColor = Application.Evaluate("GetDFColor(""" & _
rng.Parent.Name & """,""" & rng.Address() & """)")
End Function