2012-10-12 51 views
8
x = 0 
For Each cell in Sheets("01").Range("A:A").Cells 
If cell.Value = "aaa" And cell.Offset(0, 1).Value = "bbb" Then 
x = x+1 
End If 
Next cell 
MsgBox x 

有沒有更簡單的方法,請問?如何計數如果在多列中?

+0

可能重複的[COUNTIF擁有多個或標準] (http://stackoverflow.com/questions/8726627/countif-with-multiple-or-criteria) – brettdj

回答

23

你可以用一個公式做到這一點,像這樣

(Excel 2007或更高版本)

=COUNTIFS(A:A,"aaa",B:B,"bbb") 

(Excel 2003或更早)

=SUMPRODUCT(--(A:A="aaa")*--(B:B="bbb")) 

或者,如果你有用VBA做,用Evaluate

MsgBox Evaluate("=COUNTIFS(A:A,""aaa"",B:B,""bbb"")") 

MsgBox Evaluate("=SUMPRODUCT(--(A:A=""aaa"")*--(B:B=""bbb""))") 
根據您的評論

編輯

如果rDatrSecRange的,並且ct是片CodeName做這樣的

Dim rDat As Range 
Dim rSec As Range 
Set rDat = ct.[A:A] 
Set rSec = ct.[B:B] 
ct.Range("C6").Value = Evaluate("=COUNTIFS(" & rDat.Address(, , , True) & " ,""a""," & rSec.Address(, , , True) & ",""1"")") 

如果ct是表Name,使用這個

Dim ws As Worksheet 
Dim rDat As Range 
Dim rSec As Range 
Set ws = ActiveWorkbook.Worksheets("ct") 
Set rDat = ws.[A:A] 
Set rSec = ws.[B:B] 
ws.Range("C6").Value = Evaluate("=COUNTIFS(" & rDat.Address(, , , True) & " ,""a""," & rSec.Address(, , , True) & ",""1"")") 

如果rDatrSec是字符串時,使用該

Dim ws As Worksheet 
Dim rDat As String 
Dim rSec As String 
Set ws = ActiveWorkbook.Worksheets("ct") 
rDat = "ct!A:A" 
rSec = "ct!B:B" 
ws.Range("C6").Value = Evaluate("=COUNTIFS(" & rDat & " ,""a""," & rSec & ",""1"")") 

另一種選擇(對於rDatrSec作爲範圍)

ct.Range("C6").Value = Application.WorksheetFunction.CountIfs(rDat, "a", rSec, "1") 
+0

克里斯,我試過'ct.Range(「C6」)。Value = Evaluate(「= COUNTIFS(rDat,」「a」「,rSec,」「1」「)」)'#有錯誤。 ct是表單,rDat和rSec是定義的範圍。 Excel 2010 – Alegro

+0

非常感謝。已解決 – Alegro

+2

SUMPRODUCT在Google Spreadsheets中無法正常工作。 –