我具有此功能,可以通过彩色文本对单元格范围进行计数。原始功能使用两个输入(范围和文本颜色)作为参数。当我在不同的行上使用它时,我想自动计算动态单元格范围,但是我不知道如何在vba函数中管理该参数。这是我的代码。希望有人可以帮我...问候,先生。
Function CountByColor()
'Function CountByColor(rng, cell)
Application.Volatile
Set MyCell = ActiveCell.Address
ActiveCell.Offset(-1, -2).Select
Range(Selection, Selection.End(xlUp)).Select
Set MyRange = ActiveSheet.UsedRange
'Set zRange = rng
Set zRange = MyRange
Set zCell = MyCell.Offset(0, -1)
zValue = cell.Value
zFontColor = zCell.font.color
zCellColor = zCell.Interior.color
CountByColor = 0
On Error Resume Next
For Each cell In zRange
If cell.Value = zValue Then
If cell.font.color = zFontColor Then
If cell.Interior.color = zCellColor Then
CountByColor = CountByColor + 1
End If
End If
End If
Next
On Error GoTo 0
End Function
range参数是由“ activecell.offset(-1,-2).select”创建的,文本为彩色参考单元格是由“ mycell.offset(0,-1)......
答案 0 :(得分:0)
这是一种方法(从您的代码中简化了一点……)
Function countcolor()
Dim clr As Long, rng As Range, c As Range, rv As Long
With Application.ThisCell '<< ThisCell is the cell calling the function
clr = .Offset(0, -1).Interior.Color '<< color to look for...
Set rng = .Parent.Range(.Offset(-1, -2), .Offset(-1, -2).End(xlUp))
End With
For Each c In rng.Resize(, 100).Cells '<< adjust resizing to suit...
If c.Interior.Color = clr Then rv = rv + 1
Next c
countcolor = rv
End Function