![](/img/trans.png)
[英]Getting #Value! Error on worksheet, but VBA test sub returns what it should
[英]VBA function returns #VALUE! in worksheet, works as sub
我寫了一個函數,通過將值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 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.