VBA:复杂CountIf
我试图在VBA中使用多个AND参数实现一个CountIf UDF。 我已经构build了下面的代码,它给了我一个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可以是一个值或expression式,所有条件在AND条件下连接在一起
示例: COUNTIF(Range("JA:KD & i"), Sheet2.Cells(j,1) And Sheet4.Cells(i, k) = "TRUE" And Sheet4.Cells(i + 4, k) = "TRUE")
以下是您可以尝试的内容:由于我们没有看到您的工作表,因此我已经采集了我自己的示例数据。 大多数范围都是硬编码的,但是你可以改变它,并相应地使其变成dynamic的。 算术运算符是您需要手动更改的一件事情,例如<, >, =
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
输出: