我正在尝试在多个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")
答案 0 :(得分: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
输出: