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 :(得分: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""))")
编辑
如果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")