vba对于通过列的每个循环都很简单

时间:2014-03-11 21:39:49

标签: vba loops excel-vba if-statement offset

我想要一些支持来纠正这段简单的代码。运行代码时,它始终显示1,然后弹出未命中匹配错误框。我不明白为什么这不起作用代码似乎很简单。

 Sub Test3()
Dim rng As Range, cell As Range

Set rng = Range("D1:D10")

For Each cell In rng
    If cell.Value > 0 Then
    MsgBox Application.WorksheetFunction.CountA(cell.Value)
End If
Next cell

End Sub

2 个答案:

答案 0 :(得分:0)

这是一种方式:

Sub Test3()
    Dim rng As Range, cell As Range, IAmTheCount As Long
    Set rng = Range("D1:D10")
    IAmTheCount = 0
    For Each cell In rng
        If cell.Value > 0 Then
            IAmTheCount = IAmTheCount + 1
        End If
    Next cell
    MsgBox IAmTheCount
End Sub

答案 1 :(得分:0)

由于您使用的是for each循环,因此您将逐个计算单元格。这就是为什么Msgbox总是说1.你不应该使用循环来实现你想要的东西

Sub Test3()
    Dim rng As Range, cell As Range

    Set rng = Range("D1:D10")

    MsgBox Application.WorksheetFunction.CountIf(rng, ">0")

End Sub