使用VBA如何将CountIfs与变量一起使用

时间:2016-10-06 20:04:31

标签: excel-vba excel-2007 vba excel

我找不到将CountIfs与变量一起使用的示例。为什么会出现“对象需要”错误?

Dim recTable As ListObject
Dim EOM As Date
Dim Pending As Double

For x = 1 To RecordCount
    If Not IsNull(recTable.DataBodyRange(x, 7).Value) Then
                    Pending = Pending + WorksheetFunction.CountIfs(recTable.DataBodyRange(x, 2).Value, "<=" & EOM, recTable.DataBodyRange(x, 7).Value, ">" & EOM)
                ElseIf IsNull(recTable.DataBodyRange(x, 7).Value) And Not IsNull(recTable.DataBodyRange(x, 6).Value) Then
                    Pending = Pending + Application.WorksheetFunction.CountIfs(recTable.DataBodyRange(x, 2).Value, "" <= "" & EOM, recTable.DataBodyRange(x, 6).Value, "" > "" & EOM)
                Else
                    Pending = Pending + 1
            End If
        Debug.Print Pending
Next x

1 个答案:

答案 0 :(得分:1)

根据评论,我建议如下:

Dim recTable As ListObject
Dim EOM As Date
Dim Pending As Double ' Maybe Long or Integer?

'recTable is not set in the posted code, but I assume it is in the actual code
'EOM is not set in the posted code, but I assume it is in the actual code
'RecordCount is not declared or set in the posted code, but I assume it is in the actual code
'x is not declared in the posted code, but I assume it is in the actual code

With recTable
    For x = 1 To RecordCount
        If Not IsNull(.DataBodyRange(x, 7).Value) Then
            If .DataBodyRange(x, 2).Value <= EOM And _
               .DataBodyRange(x, 7).Value > EOM Then
                Pending = Pending + 1
            End If
        ElseIf Not IsNull(.DataBodyRange(x, 6).Value) Then
            If .DataBodyRange(x, 2).Value <= EOM And _
               .DataBodyRange(x, 6).Value > EOM The
                Pending = Pending + 1
            End If
        Else
            Pending = Pending + 1
        End If
        Debug.Print Pending
    Next x
End With