Application.Volatile替代自动更新UDF
我有一个函数,我从MSDN中计数一个范围内具有另一个单元格颜色的单元格的数量。
这是代码
Function countCcolor(range_data As Range, criteria As Range) As Long Application.Volatile Application.ScreenUpdating = False Dim datax As Range Dim xcolor As Long xcolor = criteria.Interior.ColorIndex For Each datax In range_data If datax.Interior.ColorIndex = xcolor Then countCcolor = countCcolor + 1 End If Next datax Application.ScreenUpdating = True End Function
这个函数的一个要求是,当一个单元的颜色值发生变化时,它将被更新。
我的想法是创build一个事件,当一个单元格的颜色改变,并重新计算任何单元格的function,但我不知道这是否是最好的方法。
您可能已经发现,更改单元格的内部颜色不会触发Sub Worksheet_Change(...)
。 由于没有价值变化,没有得到重新计算。 在这种情况下,甚至没有Application.Volatile
的帮助。
最好的方法可能是使用Worksheet_SelectionChange(...)
,最终与Worksheet_Activate(...)
和Worksheet_Deactivate(...)
结合使用Worksheet_Activate(...)
在进入和离开时清理表单)来调用强制重新计算,例如
Sub DoMyRecalc() ' Range("OutputRange").Calculate ' all uses of countCcolor() within that range ' [H3].Calculate ' countCcolor() only used in cell H3 End Sub Private Sub Worksheet_SelectionChange(ByVal Target As Range) DoMyRecalc End Sub Private Sub Worksheet_Activate() DoMyRecalc End Sub Private Sub Worksheet_Deactivate() DoMyRecalc End Sub