输出错误的Excel-VBA代码

时间:2018-01-22 17:39:05

标签: excel-vba vba excel

enter image description here当我执行此函数时,我得到一个错误的输出,即45(整个范围内的单元格数),而正确的答案出现在功能对话框中,如屏幕截图所示。 Correct result is 15

我的代码:

Function Countcolor(CountRange As Range, ColorRange As Range)
    Dim Rng As Range
    Dim xBackColor As Long
    On Error Resume Next
    For Each Rng In CountRange
        qqq = Rng.Value
        xxx = Rng.DisplayFormat.Interior.Color
        If Rng.DisplayFormat.Interior.Color = ColorRange.DisplayFormat.Interior.Color Then
            xBackColor = xBackColor + 1
        End If
   Next

   Countcolor = xBackColor

  End Function

我正在将此工具转换为函数:

Sub DisplayFormatCount()
    'Updateby20150305
    Dim Rng As Range
    Dim CountRange As Range
    Dim ColorRange As Range
    Dim xBackColor As Long
    Dim xFontColor As Long
    On Error Resume Next
    xTitleId       = "KutoolsforExcel"
    Set CountRange = Application.Selection
    Set CountRange = Application.InputBox("Count Range :", xTitleId, CountRange.Address, Type: = 8)
    Set ColorRange = Application.InputBox("Color Range(single cell):", xTitleId, Type: = 8)
    Set ColorRange = ColorRange.Range("A1")
    xReturn        = 0
    For Each Rng In CountRange
        qqq           = Rng.Value
        xxx           = Rng.DisplayFormat.Interior.Color
        If Rng.DisplayFormat.Interior.Color = ColorRange.DisplayFormat.Interior.Color Then
            xBackColor   = xBackColor + 1
        End If
        If Rng.DisplayFormat.Font.Color = ColorRange.DisplayFormat.Font.Color Then
            xFontColor = xFontColor + 1
        End If
    Next
    MsgBox "BackColor is " & xBackColor & Chr(10) & "FontColor is " & xFontColor
End Sub

提前致谢,感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

试试这个。这对我来说可以计算范围的内部颜色

Function Countcolor(CountRange As Range, ColorRange As Range) As Long

Dim Rng As Range
Dim xBackColor As Long
xBackColor = ColorRange.Interior.Color

For Each Rng In CountRange
    If Rng.Interior.Color = xBackColor Then Countcolor = Countcolor + 1
Next Rng

End Function