简体   繁体   中英

With VBA how to use CountIfs with a variable

I cannot find an example anywhere of using CountIfs with a variable. Why is this giving an "Object Requried" error?

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

Based on comments, I recommend the following:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM