Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to CountIf in multiple columns?

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

Is there a shorter way, pls ?

like image 217
Alegro Avatar asked Oct 12 '12 09:10

Alegro


People also ask

Can you have 2 Countifs in Excel?

#3 Count Cells with Multiple Criteria – Between Two Dates To get a count of values between two values, we need to use multiple criteria in the COUNTIF function. We can do this using two methods – One single COUNTIFS function or two COUNTIF functions.

Can you use Countif for 3 criteria?

A number, expression, cell reference, or text string that determines which cells will be counted. For example, you can use a number like 32, a comparison like ">32", a cell like B4, or a word like "apples". COUNTIF uses only a single criteria.

How do I count yes in multiple columns in Excel?

1. Select a blank cell, copy and paste formula =COUNTA(B15:B21)-COUNTIF(B15:B21,"Yes")-COUNTIF(B15:B21,"No")-COUNTIF(B15:B21,"=""") into the Formula Bar, then press Enter key.

Can Countif have multiple ranges?

The COUNTIFS function applies criteria to cells across multiple ranges and counts the number of times all criteria are met. This video is part of a training course called Advanced IF functions.


1 Answers

You can do this with a formula, like this

(Excel 2007 or later)

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

(Excel 2003 or earlier)

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

Or, if you have to do it in VBA, use Evaluate

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

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

EDIT based on your comment

If rDat and rSec are Range's, and ct is the sheet CodeName do it like this

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"")")

If ct is the sheet Name, use this

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"")")

If rDat and rSec are strings, use this

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"")")

Another option (for rDat, rSec as ranges)

ct.Range("C6").Value = Application.WorksheetFunction.CountIfs(rDat, "a", rSec, "1")
like image 86
chris neilsen Avatar answered Sep 28 '22 09:09

chris neilsen