计算Colourfilled细胞的数量

时间:2016-04-15 16:03:19

标签: vba excel-vba macros excel

enter image description here我试图找到B coloumn中colourfilled细胞的数量。我想计算并显示填充色彩的颜色数量

但我收到错误:

Dim sum As Long
Dim count As Long
     sum = 0
count = 0
    strFileName = Application.GetOpenFilename("Excel files (*.xls*),*.xl*", Title:="Open data")
    Set Target = Workbooks.Open(strFileName)
    Set tabWS = Target.Worksheets("Tabelle1")

    ' lastrow = tabWS.Range("D" & tabWS.Rows.count).End(xlUp).Row  'Trigger Description starts from 2 row A coloumn
        lastrow = tabWS.Range("B" & tabWS.Rows.count).End(xlUp).Row  'Trigger Description starts from 2 row A coloumn
        For j = 2 To lastrow
        If tabWS.Cells(j, 2).Interior.ColorIndex = 4 Then
        sum = sum + tabWS.Cells(j, 8).value
        count = count + 1
        End If
        Next j

        MsgBox ("the value is" & sum)
        End sub

我得到sum = sum + tabs.cell(j,8).value

的错误

我无法弄清楚为什么我收到此错误。任何人都可以给我一个建议

1 个答案:

答案 0 :(得分:1)

每次在tabWS上使用方法时,我都希望您能够打开工作簿。尝试将tabWS设置为等于以下内容:

tabWS = Worksheets("Tabelle1")

现在,当您在代码的后半部分设置lastrow和sum变量时,您将无法一遍又一遍地尝试打开工作簿。

编辑(从下面的评论继续)*:

    lastrow = Worksheets("Tabelle1").Range("B" & Worksheets("Tabelle1").Rows.count).End(xlUp).Row  
    For j = 2 To lastrow
    If Worksheets("Tabelle1").Cells(j, 2).Interior.ColorIndex = 4 Then
    sum = sum + Worksheets("Tabelle1").Cells(j, 8).value
    count = count + 1
    End If
    Next j

    MsgBox ("the value is" & sum)
    End sub