VBA函数返回#VALUE! 在工作表中,作为子工作

我已经写了一个函数,通过为不同的有条件格式化的单元格赋值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 

我错过了什么区别使得这个function不起作用?

以下是解决方法的一个基本示例:

 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