Excel VBA修改

我有一个函数的VBA代码,如果它们具有特定的背景填充颜色(由引用单元格给出),则计数或相加单元格:

Function ColorFunction(rColor As Range, rRange As Range, Optional SUM As Boolean) Dim rCell As Range Dim lCol As Long Dim vResult lCol = rColor.Interior.ColorIndex If Count = True Then For Each rCell In rRange If rCell.Interior.ColorIndex = lCol Then vResult = WorksheetFunction.Count(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 

因为我不熟悉VBA环境,所以如何修改这段代码来接受2个单元格作为背景填充颜色的“基线”,如果一行单元格同时包含两个input颜色,则输出一个范围的count / sum?

首先要了解VBA,除非您指定,否则不需要variables声明 – 任何引用的新variables都会自动创build为未初始化的变体。 这对于快速编程很有用,但对玩具编程来说没有任何用处。

总是把Option Explicit作为模块中的第一行,当你使用initialied=0而不是initialized=0时,它会抛出一个错误,而不是创build一个新的variables,并且使得debugging非常困难。

在定义variables的时候,我也会使用CamelCase,并且保持小写字母的格式input – vba会根据情况进行大小写,所以如果你input了一个错误的variables,那么当你完成这个行时,它不会变成大写字母

 Dim TestIt testit = 1 'will change to TestIt = 1 testti = 1 'will not have upper case letters 

那咆哮,让我们看看这个节目。

首先我们要做的是检查你是否给了2个单元格的颜色。 这可以通过检查细胞数来完成:

 If rColor.Cells.Count <> 2 Then ... 

接下来是检查我们有至less2列检查

 If rRange.Columns.Count = 1 Then .... 

最后我们必须改变总数/总和的逻辑。 目前,它会单独检查每个单元格,并且无法查看是否在同一行上find了另一种颜色,所以我们必须更改以单独检查每一行。 这是最容易完成的2嵌套For ... Next循环

一旦我们检查了一行,那么我们需要检查是否find了两种颜色。 我们可以定义一些标志来testing。

 If rRange.Cells(LoopCols, LoopRows).Interior.ColorIndex = Color1 Then Find1stColor = True 

第二种颜色也是一样的,并在行尾查看

 If Find1stColor And Find2ndColor Then 

一旦我们定义了这个结构,我们就可以编写我们的程序:

 Option Explicit Function Color2Function(rColor As Range, rRange As Range, Optional SUM As Boolean) Dim RowCount As Long Dim ColCount As Long Dim tempResult Dim Color1 As Long Dim Color2 As Long Dim Totals Dim LoopRows As Long Dim LoopCols As Long Dim Find1stColor As Boolean Dim Find2ndColor As Boolean If rColor.Cells.Count <> 2 Then Color2Function = CVErr(xlErrRef) 'Error 2023 returns #REF! Exit Function End If Color1 = rColor.Cells(1).Interior.ColorIndex Color2 = rColor.Cells(2).Interior.ColorIndex RowCount = rRange.Rows.Count ColCount = rRange.Columns.Count If ColCount = 1 Then Color2Function = 0 ' one column can never contain 2 colors Exit Function End If For LoopRows = 1 To RowCount Find1stColor = False Find2ndColor = False tempResult = 0 For LoopCols = 1 To ColCount If rRange.Cells(LoopCols, LoopRows).Interior.ColorIndex = Color1 Then Find1stColor = True tempResult = tempResult + rRange.Cells(LoopCols, LoopRows).Value End If If rRange.Cells(LoopCols, LoopRows).Interior.ColorIndex = Color1 Then Find2ndColor = True tempResult = tempResult + rRange.Cells(LoopCols, LoopRows).Value End If Next If Find1stColor And Find2ndColor Then If SUM Then Totals = Totals + tempResult Else Totals = Totals + 1 End If End If Next Color2Function = Totals End Function 

如果其中一种颜色被发现多次,我就把它作为一个练习来决定该怎么做。