2013-01-23 93 views
1

我想在VBA中用多個AND參數實現一個CountIf UDF。我已經構建了下面的代碼,它給了我一個app-defined or obj errorVBA:複雜CountIf

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, ...) 當條件1可以是一個值或表達 和所有條件都結合在一起在AND條件

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

+0

這永遠不會工作:'Sheet9.Range( 「JA:KD&I」)'。我希望你可能想要像'Sheet9.Range(「JA」&i&「:KD」&i)''。但是,這可能無法按預期方式工作,因爲您正在將一組值與一個值進行比較。哪一行代碼有問題? – mkingston

+0

嗨,所以你想要計算範圍JA6中的單元格數量:KD(lastRow)匹配3個條件。 (AND condition) Sheet2.Cells(j,1),Sheet4.cells(i,k),Sheet4.cells(i + 4,k)? 而且這3個單元也可以是表達式,例如, 「> 2000」? – Larry

+1

也不應該'count'在循環之外嗎?我也無法真正理解你的例子。你能上傳截圖或數據例子嗎? –

回答

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 

輸出:

enter image description here