如何持续运行计数黄细胞的功能



我在Excel中有一个函数,它可以将行中有多少个黄色单元格相加。

 Function CountColorIf(rArea As Range) As Long
    Dim rAreaCell As Range
    Dim lCounter As Long
    For Each rAreaCell In rArea
        If rAreaCell.Interior.ColorIndex = 6 Then
            lCounter = lCounter + 1
        End If
    Next rAreaCell
    CountColorIf = lCounter
End Function

代码可以工作,但不是立即工作。例如,假设我将其中两个单元格设置为黄色,那么我必须单击放置该函数的单元格并按enter键以显示正确的数字。

如何在工作表更改时使其运行?

我确实找到了一些关于工作表的东西。事件(类似的东西),但从我的理解,这只适用于子,而不是一个函数。

您可以将函数标记为Volatile,以便每次有更改时都重新调用它。这可能非常占用CPU,因为即使输入一个数字也会导致它运行。

Application.Volatile (True)

编辑:这对你不起作用

原因:更改单元格的内部颜色不会触发worksheet_change事件。我为虚假的希望感到抱歉。我将保留答案,以消除您对工作表更改事件的疑虑,但它不适用于您的情况。


应用程序以外。Volatile是Worksheet_Change事件。只要工作表中有变化,它就会启动。如果你的电子表格比较大,我把一些东西关掉,这样就可以节省资源。

为了工作,它需要粘贴在你的工作表的代码(不是一个模块)。

Private Sub Worksheet_Change(ByVal Target As Excel.Range)
    Dim rng as Range
    Application.enableevents = False
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    If Not Intersect(Target, Sheet1.Cells) Is Nothing Then
        set rng = ActiveCell.Entirerow
        msgbox "There are " & CountColorIf(rng) & " yellow cells in this row!"
    End If
    Application.ScreenUpdating = True
    Application.enableevents = True
    Application.Calculation = xlCalculationAutomatic                    
End Sub

最新更新