在Excel中使用UDF的单元格不会重新计算

时间:2016-01-01 21:27:42

标签: excel vba udf

我编写了这个简单的UDF来在Excel电子表格中进行计算。代码似乎工作正常,但只有一次。但是,如果我更改表中的值(SharePriceGrowthTable),则不会更新单元格中的结果。即使我按F9重新计算工作表,也不会更新使用该功能的单元格中的值。我已经验证计算选项设置为自动。

有关正在发生的事情或我需要做些什么不同的任何想法?

'Compute Stock Growth Score
Function StockGrowthScore(GrowthPercent As Double) As Double

 Dim ScoreTable As Range

 Set ScoreTable = Range("SharePriceGrowthTable")

 If GrowthPercent >= 0 Then
   StockGrowthScore = WorksheetFunction.VLookup(GrowthPercent, ScoreTable, 2)
 Else
   StockGrowthScore = -WorksheetFunction.VLookup(-GrowthPercent, ScoreTable, 2)
 End If

 StockGrowthScore = Application.Round(StockGrowthScore, 3)

End Function

2 个答案:

答案 0 :(得分:0)

在自动计算模式下,如果在公式中引用显式的范围内发生更改,则会重新计算UDF公式。在您的情况下,代码中引用了<div>,但公式中没有引用。

可能的解决方法是使范围本身成为UDF的参数:

Range("SharePriceGrowthTable")

现在明确地将范围Function StockGrowthScore(GrowthPercent As Double, tbl as Range) As Double 传递给公式中的第二个参数。

答案 1 :(得分:0)

问题在于设置函数内的范围。一种解决方案是将Range作为参数传递:

Function StockGrowthScore(GrowthPercent As Double, ScoreTable As Range) As Double
    If GrowthPercent >= 0 Then
        StockGrowthScore = WorksheetFunction.VLookup(GrowthPercent, ScoreTable, 2)
    Else
        StockGrowthScore = -WorksheetFunction.VLookup(-GrowthPercent, ScoreTable, 2)
    End If

    StockGrowthScore = Application.Round(StockGrowthScore, 3)
End Function

(称为=StockGrowthScore(1, SharePriceGrowthTable)

如果所有内容都在同一个工作表中,另一个解决方案是创建函数Volatile,尽管由于使用Application.Volatile的开销,第一个选项可能更好:

Function StockGrowthScore(GrowthPercent As Double) As Double
    Application.Volatile
    Dim ScoreTable As Range
    Set ScoreTable = Range("SharePriceGrowthTable")

    If GrowthPercent >= 0 Then
        StockGrowthScore = WorksheetFunction.VLookup(GrowthPercent, ScoreTable, 2)
    Else
        StockGrowthScore = -WorksheetFunction.VLookup(-GrowthPercent, ScoreTable, 2)
    End If

    StockGrowthScore = Application.Round(StockGrowthScore, 3)
End Function