1

我正在尝试使用多个 AND 参数在 VBA 中实现 CountIf UDF。我构建了以下代码,它给了我一个app-defined or obj error.

Sub Count_PoA()
    Dim LastRow As Long
    With ActiveSheet
        LastRow = .Cells(.Rows.Count, "C").End(xlUp).Row - 5
    End With

    For i = 6 To LastRow
        Count = 0
        For j = 17 To 58
            For k = 12 To 397 Step 13
                If Sheet9.Range("JA:KD & i") = Sheet2.Cells(1, j) And Sheet4.Cells(i, k) = "TRUE" And Sheet4.Cells(i + 4, k) = "TRUE" Then
                    Count = Count + 1
                End If
                Count = Sheet2.Range("B" & j)
            Next
        Next
    Next
End Sub

理想情况下,我想要相当于:

COUNIF(Dim someRange as Range, condition1, condition2, condtion3, ...) 其中 condition1 可以是一个值或表达式,并且所有条件都在 AND 条件中连接在一起

例子: COUNTIF(Range("JA:KD & i"), Sheet2.Cells(j,1) And Sheet4.Cells(i, k) = "TRUE" And Sheet4.Cells(i + 4, k) = "TRUE")

4

1 回答 1

2

您可以尝试以下方法:因为我们没有看到您的工作表,所以我采用了自己的样本数据。大多数范围都是硬编码的,但您可以更改它并相应地使其动态化。算术运算符是您需要手动更改的一件事,例如<, >, =

Option Explicit

Sub myCountIFS()
Dim counts As Integer, i As Integer
Dim LastRow As Long
Dim vArray1 As Variant
Dim cnd1 As String, cnd2 As String, cnd3 As String

LastRow = Sheets(1).Cells(Sheets(1).Rows.Count, "B").End(xlUp).Row - 1
vArray1 = WorksheetFunction.Transpose(WorksheetFunction.Transpose(Sheets(1).Range("B2").Resize(LastRow, 3).Value))

cnd1 = Sheets(1).Range("F2").Value
cnd2 = Sheets(1).Range("G2").Value
cnd3 = Sheets(1).Range("H2").Value

For i = LBound(vArray1) To UBound(vArray1)
    If vArray1(i, 1) = cnd1 And vArray1(i, 2) = cnd2 And vArray1(i, 3) < CInt(cnd3) Then
        counts = counts + 1
    End If
Next i

Sheets(1).Range("I2") = counts

End Sub

输出:

在此处输入图像描述

于 2013-01-23T07:05:09.790 回答