COUNTIF in 5 languages (VBA/SQL/PYTHON/M query/DAX powerBI) | by Aymen | Towards Data Science

Excel is a powerful spreadsheet used by most people working in data analysis. The increase of volume of data and development user-friendly tools is an opportunity of improvement of Excel reports by mixing them with another tool or language.
As working for a financial reporting department I faced the need to boost our reporting tools. A simple way to start working with a new language is to translate what we use to do in excel, in another language. “How can I pivot this?”, “How can I vlookup that?”.
In this article I will share with you how you can make COUNTIF in 5 different languages: VBA, python, SQL, DAX (Power BI), M (Power query). it will simple tips but if you want to get more detailed article don’t forget to follow me!
COUNTIF is one of the statistical function of Excel to count the number of cells that meet a criterion.
The simplest way of using it is as follow:
=COUNTIF(Where do you want to look?, What do you want to look for?)
But in the part “What do you want to look for?” you can put a conditional criteria ( it could be logical operator (<,>,<>,=) and wildcards (*,$) for partial conditions).
In this article I will use a similar example as another article I wrote to present the SUMIF in 5 languages:
towardsdatascience.com
It will be a tab with a list of items In cell C2 we can put a COUNTIF formula with arguments : Range=A2:A8, Criteria=cell(A2). So basically we count the number of “Item1” in our list.
=COUNTIF(A1:A8,A2)
Visual Basic for Application (VBA) is an implementation of Microsoft Visual Basic integrated into Microsoft Office applications.
On your code, you can set up a variable to store the result of the COUNTIF result using the statement “WorksheetFunction.sumif”. It works exactly as the function itself. Then you can store the result directly into cell C2.
Range(“C2”) = WorksheetFunction.COUNTIF(Range(“A2:A8”), Range(“A2”))
Let’s do it properly by declaring variables now:
Sub sumif()Dim wb As WorkbookDim wsD As WorksheetDim Arg1 As RangeDim Arg2 As RangeDim Arg3 As RangeSet wb = ThisWorkbookSet wsD = wb.Worksheets("Sheet1")Set Arg1 = wsD.Range("A2:A8") 'where to findSet Arg2 = wsD.Range("A2") 'what to findRange(“C2”)= Application.WorksheetFunction.SUMIF(Arg1, Arg2)End Sub
SQL ( Structured Query Language) or sequel, is a standard language for storing, manipulating and retrieving data in databases. It is one of the common upgrade done by companies that face limits with Excel. Usually, the first reaction is to negotiate some budget in order to store the data into a database and use SQL to “speak” with this database and organise, manipulate the data. The language is also highly appreciable. Close to a natural language, you don’t feel coding when typing simple SQL request.
Let’s start with creating a table with items:
CREATE TABLE table1 (    Item varchar(255)   );INSERT INTO table1VALUES ('Item1');INSERT INTO table1VALUES ('Item2');INSERT INTO table1VALUES ('Item1');INSERT INTO table1VALUES ('Item3');INSERT INTO table1VALUES ('Item1');INSERT INTO table1VALUES ('Item4');INSERT INTO table1VALUES ('Item4');SELECT*FROM TABLE1;
Here is the result:
Then keep in mind that in SQL, when you want to get an information you will often use the expression SELECT. Basically in SQL you play with data, tables and relationship. So you have to understand well the “how I can get this information” in order to SELECT it:
SELECT “How I will get what I want” FROM “Were I have to apply the How”.
So in our case we will select the count of the case where the items of the column “Item” equals “Item1”. Let’s write the formula and then analyze it:
SELECT COUNT(CASE WHEN Item = 'Item1' THEN 1 END) FROM table1;
So we SELECT the COUNT of the CASE WHEN (CASE in SQL is a kind of “IF” function) Item='Item1' THEN (if it’s the case) we count 1. And this applied in table1.
Result:
Python is an interpreted, high level language with a generic purpose. It is used in a large range of application, including data analysis. We can present python by saying “For all application its libraries”. And for data, without surprise, we will use the famous Pandas.
There are several ways to COUNTIF in python. We could play with a dataframe, columns, group by etc. But here I will simply create a list with all items, then loop into this list and add 1 every time that the loop meet an “Item1”. All this stored in a variable result:
items =['Item1','Item2','Item1','Item3','Item1','Item4','Item4']res = sum(1 for i in items if i == 'Item1')
Here is the result:
M is the powerful language behind the tool power query. Even if you are working on the query editor, every single step will be written in M. M stands for Data Mashup or Data Modeling. I highly recommend to have a look at this language, we can do so much more than just using the graphical interface.
Regarding the COUNTIF, the graphical interface is so smooth that we can directly use it. You just have to import your table into the graphical interface and then use the filter in the column Item:
Then you select the column “Items”, and on the field Transform do the COUNT:
And you get the count. Another way is to use the Group By in button in the left, but in the scale of our example, it will add more step that we can skip by directly filter and count. I will present this with another feature where it will be more useful (The pivot table).
DAX stands for Data Analysis Expressions. More than a language, it is a library of functions and operators that can be used to build formulas in Power BI and Power Pivot.
The COUNTIF is a good opportunity to introduce the function CALCULATE. It is one of the most famous function in Power BI that evaluates an expression after applying a filtering rule. It is more close to the COUNTIFS as you can apply several filters arguments.
CALCULATE(<expression>[, <filter1> [, <filter2> [, ...]]])
Expression: is the expression to be evaluated.
Filter1,2,...: can be a Boolean expression, a table filter or even another function.
In our case, the expression to be evaluated is the count of Table1 items, by applying one filter table in column “Items”=”Item1"
countif = CALCULATE(COUNTA(Table1[Items]),Table1[Items] = 'Item1')
This article is a part of a set of articles where I share my way of doing an Excel feature in other languages. For sure, when you decide to move from Excel to programming, your approach of data analysis will totally change and you will learn that there are tons of way to get to your solution. If you have another manner to do this or even know how to do it with other languages, feel free to share them in the comments or by contacting me in my social networks! I will be pleased to read your thoughts!