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
有沒有更簡單的方法,請問?如何計數如果在多列中?
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
有沒有更簡單的方法,請問?如何計數如果在多列中?
你可以用一個公式做到這一點,像這樣
(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""))")
根據您的評論
編輯
如果rDat
和rSec
是Range
的,並且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"")")
如果rDat
和rSec
是字符串時,使用該
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"")")
另一種選擇(對於rDat
,rSec
作爲範圍)
ct.Range("C6").Value = Application.WorksheetFunction.CountIfs(rDat, "a", rSec, "1")
可能重複的[COUNTIF擁有多個或標準] (http://stackoverflow.com/questions/8726627/countif-with-multiple-or-criteria) – brettdj