datax的udf_替代Application.Volatile自动更新UDF

bd96500e110b49cbb3cd949968f18be7.png

I have a function i got off of MSDN that counts the number of cells in a range that have a another cells color.

Here is the code

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

A requirement for this function is that it will update when ever a color value of a cell changes.

My idea is to create an event for when ever the color of a cell is changed and have it recalculate the any cell with the function but I'm not sure if this is the best way.

解决方案

You may have already found out that changing a cell's interior color doesn't fire a Sub Worksheet_Change(...). As no value is changed, nothing gets recalculated. In this case not even the Application.Volatile is of help.

The best approach might be to use a Worksheet_SelectionChange(...), eventually in combination with Worksheet_Activate(...) and Worksheet_Deactivate(...) (to have the sheet clean upon entry and leave) to call for an enforced recalculation, e.g.

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值