使自定义Excel VBAfunction更快

我有一个自定义函数,用来计算或总结我有多less个彩色单元格。 这是function:

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 

通过input以下函数来调用它:

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

要么

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

哪里:

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

我的问题是: 有什么我可以做的VBA来加快这个function?

我试图用WorksheetFunction部分进行实验,但无法find可用的语法。 任何其他的想法?

尝试一下:

 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 

添加了“作为变种”