使自定义Excel VBA功能更快

时间:2016-08-11 11:51:35

标签: excel vba colors

我有一个自定义函数,用于计算或总计我有多少个彩色单元格。这是功能:

Function ColorFunction(rColor As Range, rRange As Range, Optional SUM As Boolean)

    Application.Volatile (True)

    Dim rCell As Range
    Dim lCol As Long
    Dim vResult

    lCol = rColor.Interior.ColorIndex

    If SUM = True Then
        For Each rCell In rRange
            If rCell.Interior.ColorIndex = lCol Then
                vResult = WorksheetFunction.SUM(rCell, vResult)
            End If
        Next rCell
    Else
        For Each rCell In rRange
            If rCell.Interior.ColorIndex = lCol Then
                vResult = 1 + vResult
            End If
        Next rCell
    End If

ColorFunction = vResult

End Function

通过输入以下函数调用它:

=colorfunction($A$1,A2:C2,FALSE)

=colorfunction($A$1,A2:C2,TRUE)

其中:

  • A1 =要检查背景颜色的单元格
  • A2:C2 =要计算的范围
  • FALSE / TRUE = Count或Sum

我的问题是:我可以对VBA做些什么来加速这个功能?

我尝试使用WorksheetFunction部分进行试验,但无法找到有效的语法。还有其他想法吗?

1 个答案:

答案 0 :(得分:0)

试一试:

Function ColorFunction2(rColor As Range, rRange As Range, _
                        Optional pSUM As Boolean) As Variant
Dim rCell As Range
Dim lCol As Long
Dim vResult As Variant, vTmp As Variant ' for intermediate calcs, _
                                          for clear vision of logic, _
                                          for not doubling code
    Application.Volatile (True)

    lCol = rColor.Interior.ColorIndex

    For Each rCell In rRange.Cells ' expicit .Cells
        If rCell.Interior.ColorIndex = lCol Then
            Select Case pSUM ' SUM is reserved word
                Case True:  vTmp = rCell.Value ' out of sheet functions calling
                Case False: vTmp = 1
        ' change True-False sequence according to real probability they occures
            End Select
        End If
        vResult = vResult + vTmp
    Next ' rCell ' No need

    ColorFunction2 = vResult
End Function

添加expicit“As Variant”