Learning how to rank data within specific groups is a valuable Excel skill that can help you organize and analyze information more effectively. By using the COUNTIFS function, you can easily determine the ranking position of elements within their respective categories without manual calculation, saving time and enhancing your data analysis capabilities.
This technique is particularly useful when working with sales data, performance metrics, or any dataset where you need to identify top performers within different categories.
In my video, I demonstrate how to implement ranking within groups using a practical example:
Understanding Rank in Groups
When analyzing data, we often need to rank items not just overall but within specific categories or groups. For example, you might want to know which salesperson performed best in each region, or which product sold most in each store. This is where ranking within groups becomes essential.
In my demonstration, I work with a dataset that’s sorted by town (our grouping variable) and color-coded for easier visualization. The data includes different towns like Moria, Ironforge, and Azmarin, with each town representing a distinct group for our ranking purposes.
What makes this technique powerful is that you can immediately see how items rank within their specific categories rather than just seeing an overall ranking that might be dominated by one particular group. This provides much more actionable insights for decision-making.
Using COUNTIFS for Group Ranking
The core of this technique relies on Excel’s COUNT_IFS function, which allows us to count rows where multiple criteria are met simultaneously. This is perfect for our group ranking because we need to check two things at once: whether a row belongs to the same group as our current row, and whether its value is greater than or equal to our current row’s value.
group_range — This is the column containing our grouping variable (town names in column A)
current_group — This refers to the town in the current row we’re evaluating (A2 for the first data row)
value_range — The column containing the values we want to rank (revenue)
current_value — The specific value in the current row that we’re trying to rank
Step-by-Step Implementation
To implement this ranking system in your own spreadsheet, follow these steps:
1. First, ensure your data is organized with a clear grouping variable (like town, region, category, etc.)
2. Create a new column for your rank results
3. In this column, enter the COUNTIFS formula, which will:
Check the group column to find rows in the same group as the current row
Check the value column to find values greater than or equal to the current row’s value
Count how many rows meet both criteria — this count becomes the rank
The formula uses absolute references (with F4 to create $ signs) for the ranges and relative references for the current values. This ensures that when you copy the formula down, it still refers to the correct columns while adapting to each row’s specific values.
Analyzing the Results
After applying the COUNTIFS formula to our data, we can see that each item gets a rank within its group. In our example:
For the town of Moria, we have ranks from 1 to 5
For Ironforge, ranks range from 1 to 4
For Azmarin, ranks go from 1 to 3
What’s particularly noteworthy is that the ranks don’t have to appear in sequence in your spreadsheet. When we sort the entire dataset by revenue from largest to smallest, we can see that the highest-ranked items from each town appear mixed together. For example, after the top performers from Moria, we might see Ironforge’s top performer, then more from Moria, then perhaps Azmarin’s best.
This demonstrates how our ranking works independently within each group, regardless of where the items appear in the sorted list. The second-ranked item in Azmarin might appear as the tenth row in our sorted data, but it still correctly shows as rank 2 within its group.
Practical Applications
This ranking technique has numerous practical applications:
Sales analysis — Identify top-performing products within each category
Employee performance — Rank staff within departments or regions
Tournament results — Rank competitors within age groups or divisions
Academic performance — Rank students within classes or subjects
Market analysis — Compare performance of stocks within industry sectors
By implementing this group ranking system, you can quickly identify patterns that might otherwise be obscured when looking at data as a whole. It allows you to make fair comparisons within relevant peer groups rather than across dissimilar categories.
Additional Tips for Working with Group Rankings
When implementing group rankings in your spreadsheets, consider these helpful tips:
Color-coding your data by groups (as shown in my video) makes it much easier to visually identify the different categories and understand the rankings at a glance.
You can easily modify the ranking logic by changing the operator in the formula. For example, if you want to rank from smallest to largest instead, you would use “<=” instead of “>=” in your COUNTIFS formula.
For ties (when multiple items have the same value), this formula will assign the same rank to all tied items. If you need to handle ties differently, you might need to use more complex formulas or additional columns.
Remember that this technique works with any type of numerical data you want to rank — sales figures, scores, times, quantities, or any other measurable metric — as long as you have a clear grouping variable.
Pivot tables offer a powerful way to analyze data, particularly when you need to understand proportions within hierarchical categories. In this tutorial, I’ll show you how to quickly add sums in a pivot table and display values as a percentage of their parent row, allowing for immediate visualization of how individual items contribute to their category totals.
This technique is especially valuable when analyzing sales data across product categories and individual items.
Watch my step-by-step video tutorial below to see this process in action:
Setting Up Your Pivot Table
To begin creating an informative pivot table with percentage calculations, we need to start with a simple dataset that contains hierarchical information. In my example, I’m using a dataset that includes categories (such as fruits, vegetables, and sweets) along with the specific products within each category and their corresponding revenue figures.
The process of creating the pivot table is straightforward:
Select your data range
Navigate to the Insert tab in the Excel ribbon
Click on “Pivot Table”
Choose to place the pivot table on an existing worksheet (I selected cell F1 in my demonstration)
Click “OK” to create the basic pivot table structure
Once your pivot table framework is established, you’ll need to structure it properly to show both categories and their constituent products. In the PivotTable Fields panel, drag the appropriate fields to build your hierarchical view.
Structuring Your Pivot Table
For proper hierarchical analysis, you’ll want to arrange your fields in a logical order. In the Rows section of the PivotTable Fields panel, add your Category field first, followed by the Product field. This creates a nested structure where products appear under their respective categories.
For the values section, we need to add the Revenue field twice — once to show the raw sum and once to show the percentage of parent. Simply drag the Revenue field to the Values area twice. By default, Excel will sum these values, which is exactly what we want for this analysis.
Changing the Layout
By default, Excel displays pivot tables in compact form, but for better readability, I prefer the tabular layout. To change this:
Go to the Design tab under PivotTable Tools
Click on “Report Layout”
Select “Show in Tabular Form”
This adjustment separates the Category and Product into distinct columns, making your data more readable and easier to analyze at a glance.
Adding Percentage of Parent Row
Now comes the key part — transforming one of our revenue columns to show percentage of parent row. This calculation will show how each product contributes proportionally to its category total, and how each category contributes to the grand total. Follow these steps:
Right-click on any cell within the second Sum of Revenue column
Select “Show Values As” from the context menu
Choose “% of Parent Row Total”
This simple change transforms the raw numbers into percentages, giving you immediate insight into the proportional contribution of each item. For instance, in my example, you can now see that apples represent approximately 35% of all fruit sales, while the fruits category as a whole represents about 41% of total sales across all categories.
Understanding the Results
After applying the percentage of parent row calculation, your pivot table automatically adjusts to show meaningful proportions at every level:
Individual products show their percentage contribution to their immediate category
Category subtotals show their percentage contribution to the grand total
The grand total always equals 100%
In my demonstration, this clearly showed that sweets accounted for approximately 40% of total sales, vegetables for about 18%, and fruits for approximately 41%. Within each category, you can similarly see the proportional contribution of each product.
Finalizing Your Pivot Table
To make your pivot table more understandable, it’s important to rename the column headers to accurately reflect what each column represents. In our case:
Change the heading of the first sum column to simply read “Sum”
Rename the second column to “Percentage of Parent”
These descriptive headers ensure that anyone viewing your pivot table will immediately understand what the numbers represent without needing additional explanation.
With these adjustments complete, you now have a comprehensive pivot table that not only shows the raw revenue figures but also clearly illustrates the proportional relationships between categories and their constituent products. This dual-view approach provides both absolute and relative perspectives on your data, enabling more nuanced analysis and decision-making.
This technique is particularly valuable when analyzing sales performance, budget allocations, or any hierarchical data where understanding proportional relationships is important. By visualizing both raw numbers and percentages simultaneously, you gain deeper insights into your data structure and can more effectively communicate those insights to others.
In this tutorial, I demonstrate a practical application of recursive functions in Power Query to calculate hierarchy levels in organizational structures or MLM systems. Using a custom function with recursion, we can efficiently determine each person’s position in a hierarchical structure based on their referrer relationships, providing valuable insights for organizational analysis and reporting.
Understanding hierarchy levels is essential for visualizing reporting structures, tracking MLM downlines, or mapping any parent-child relationships in your data.
Understanding the Problem: Hierarchy Levels in Organizations
In many organizational structures, particularly in multi-level marketing (MLM) systems or corporate hierarchies, understanding the level depth of each member is crucial. The level represents how many steps a person is from the top of the organization. For instance, in our example, John is at the top (level 0), N is directly below John (level 1), and Thomas is below N (level 2).
Our sample data contains an ID column that uniquely identifies each person and a Referrer column that indicates who brought that person into the organization. The referral relationship establishes the hierarchical structure we need to analyze. Our goal is to calculate each person’s hierarchy level automatically using Power Query’s recursive capabilities.
Setting Up Power Query
To begin working with our data, we need to import it into Power Query where we can create and apply our recursive function:
Select any cell in your data table
Go to the Data tab
Click From Table/Range to import your data into Power Query
This imports your data containing the ID and Referrer columns into the Power Query Editor, where we can start building our solution.
Creating a Recursive Function to Calculate Hierarchy Levels
The core of our solution is a custom function that can call itself (recursion) to track up through the hierarchy until it reaches the top. Here’s how to create it:
In the Power Query Editor, go to the Home tab
Click New Source > Other Sources > Blank Query
Now we need to define our function. Our function will require two parameters: the person’s ID we want to calculate the level for and the complete table of people data to reference. The function will:
Find the row for the current person
Get their referrer’s ID
Check if they have a referrer
If they don’t (they’re at the top), return 0
If they do have a referrer, call the same function for the referrer and add 1 to the result
The M code for our function looks like this:
(personID, personTable) =>
let
personRow = Table.SelectRows(personTable, each [ID] = personID){0},
personAboveID = personRow[Referrer],
result = if personAboveID = null
then 0
else @HierarchyLevel(personAboveID, personTable) + 1
in
result
Make sure to name your function HierarchyLevel so that the recursive reference to itself works properly. The @ symbol in front of the function name emphasizes that we’re calling the same function again.
Applying the Function to Our Data
After creating our function, we need to apply it to every row in our data table:
Go back to your main query with the imported data
Click Add Column > Invoke Custom Function
Select your HierarchyLevel function
For personID, select the ID column
For personTable, we need to reference the current table
When setting the personTable parameter, we initially might try to reference a column name, but this will generate errors. Instead, we need to reference the entire table from the previous step. In Power Query, we can do this by referring to the previous step name.
Once correctly configured, the function will calculate the hierarchy level for each person in our table. Thomas, who is referred by N (ID 2) who in turn is referred by John (ID 1), will show as level 2. John, who has no referrer, will be at level 0.
Testing and Validating the Recursion
To verify our function works correctly, we can examine the calculated levels for each person in our organization:
John (ID 1): Level 0 (top of hierarchy, no referrer)
Anne (ID 2): Level 1 (referred by John)
Thomas (ID 5): Level 2 (referred by Anne)
Paul: Level 3 (referred by Thomas)
We can further test by changing referrer relationships. For example, if we change Paul’s referrer from Thomas (ID 5) to someone who is already at level 3, Paul would then become level 4. After making such changes in the source data, we can simply refresh our Power Query to see the updated hierarchy levels.
Top-level members (those with null referrers) are assigned level 0
The function will work for organizations of any depth, continuing to recurse up the chain until it reaches the top
If the data contains circular references (Person A refers to Person B who refers back to Person A), the recursion could create an infinite loop — consider adding error handling for this scenario in real applications
In a real-world scenario, you might want to enhance this function to handle more complex requirements, such as detecting circular references or processing multiple hierarchies within the same dataset.
Loading the Results Back to Excel
Once you’re satisfied with your hierarchy level calculations:
In the Power Query Editor, go to Home > Close & Load
Your data table with the new hierarchy level column will appear in Excel
Any time your hierarchy changes, simply refresh the query to recalculate all levels
This powerful technique allows you to maintain an up-to-date view of your organizational structure with minimal effort. The recursive approach efficiently handles even large hierarchies without requiring complex formulas or manual tracking.
With this solution in place, you can easily build reports and visualizations that leverage hierarchy level information, enabling better insights into your organizational structure, MLM downlines, or any hierarchical data you’re working with.
Creating a custom sequence of days in Excel can streamline scheduling for specific business needs or project timelines. By using the WORKDAY.INTL function, you can generate sequences that include only certain weekdays, allowing you to build schedules that skip specific days like Fridays or only include particular days like Mondays, Wednesdays, and Fridays.
This technique is especially valuable for planning recurring meetings, shift schedules, or delivery dates that follow non-standard patterns.
In my video, I demonstrate how to create these custom day sequences in Excel:
Standard Weekday Sequences in Excel
Excel provides a simple built-in method for creating standard weekday sequences (Monday through Friday). When you need a list of dates that excludes weekends, you can use Excel’s fill handle with the “Fill Weekdays” option. This approach is straightforward:
Enter your starting date in a cell
Hold the right mouse button and drag down as far as needed
Release and select “Fill Weekdays” from the context menu
This creates a sequence that automatically skips Saturdays and Sundays, giving you only the standard working days. However, this default method is limited to the standard Monday-Friday work week and doesn’t allow for customization.
Using WORKDAY.INTL for Custom Day Sequences
For more flexibility in day selection, Excel’s WORKDAY.INTL function becomes invaluable. This powerful function allows you to define which days of the week should be considered weekends (non-working days), effectively letting you create sequences with only your desired days.
The basic syntax of the WORKDAY.INTL function is:
start_date: The initial date from which to begin counting
days: The number of working days to add to the start date
weekend: A parameter that defines which days are considered weekends
holidays: An optional parameter for specific holiday dates to exclude
Weekend Parameter Options
The weekend parameter is what gives this function its flexibility. Excel offers multiple ways to specify which days should be treated as non-working days:
Using predefined weekend codes (1–7 for different standard weekend patterns)
Specifying a single day of the week as a weekend
Creating a custom 7‑character text string of 1s and 0s
The third option is the most versatile and the focus of my demonstration. The 7‑character string represents the days of the week starting with Monday (position 1) through Sunday (position 7). Using “0” marks a working day, while “1” marks a weekend/non-working day.
Creating Custom Day Sequences
To create a sequence that excludes specific days, we can leverage the text string weekend parameter. For example, if we want to exclude Fridays, Saturdays, and Sundays from our sequence, we would use:
=WORKDAY.INTL(start_date, 1, "0000111")
In this string, the “1“s in positions 5, 6, and 7 represent Friday, Saturday, and Sunday as non-working days, while the “0“s in positions 1–4 indicate Monday through Thursday as working days. By setting the days parameter to 1, each application of the function adds exactly one working day to the sequence.
When this formula is dragged down, it creates a sequence of dates that includes only Monday through Thursday, skipping over the days we’ve designated as “weekends.”
Example: Monday-Wednesday-Friday Sequence
If we want to create a sequence that includes only Mondays, Wednesdays, and Fridays, we would define all other days as non-working days:
=WORKDAY.INTL(start_date, 1, "0101011")
This pattern sets Tuesday, Thursday, Saturday, and Sunday as non-working days (represented by “1“s in positions 2, 4, 6, and 7), while Monday, Wednesday, and Friday remain as working days (with “0“s in positions 1, 3, and 5). When applied and dragged down, this formula creates a sequence that cycles through only the three days we want: Monday, Wednesday, Friday, Monday, Wednesday, Friday, and so on.
Practical Applications
This technique has numerous practical applications in business and personal planning:
Meeting schedules for recurring team meetings on specific days
Class or training schedules that occur on select days of the week
Shift work patterns for employees with custom working days
Delivery schedules for services that operate only on certain days
Payment or billing cycles that follow specific day patterns
By mastering the WORKDAY.INTL function with custom weekend parameters, you can create highly specialized date sequences that match exactly the pattern you need, without having to manually select or filter dates.
Additional Considerations
While the examples in my demonstration focus on the weekend parameter, remember that the WORKDAY.INTL function also accepts a holidays parameter which can further refine your date sequences by excluding specific holiday dates.
For more complex scheduling needs, you might combine this function with other Excel features like conditional formatting to highlight certain dates or custom number formatting to display the dates in your preferred format.
The beauty of using functions like WORKDAY.INTL is that your sequences will automatically adjust if you change the starting date, making this a dynamic solution for scheduling that can be easily updated as needed.
Excel VBA — How Absolute and relative references in macros | Introduction to macros and VBA 05
Today, we will talk about absolute and relative references in macros as well as different ways to run our macro.
Today, we are going to record a macro, where we will put the TODAY function. However this time, we will press ENTER instead of the Ctrl + Enter shortcut. We can start with cell A5. Let’s use the Record button located in the status bar tab this time instead of using the Developer tab (Fig. 1)
Fig. 1 Record button
Let’s call our macro ‘Today2’. We dont’t need any shortcut but let’s try to add a shortcut here by clicking the Ctrl + D combination and see what happens later on. We want to save our macro in the Personal Macro Workbook. When we press OK, Excel won’t allow us to save our macro, because we already have a macro with this shortcut. Let’s delete the shortcut then. When we use a shortcut that already exists in Excel, macro shortcut for macro will be more important than the default shortcut, e.g. Ctrl key. Thus, we shouldn’t use such kind of shortcuts. Let’s press OK (Fig. 2)
Fig. 2 Record Macro window
Now, we just write TODAY in cell A5. It’s important that the Use Relative References isn’t highlighted (Fig. 3)
Fig. 3 Use Relative References not highlighted
After we finished writing TODAY, let’s press ENTER. After writing the formula, we can see that Excel went down one cell by default. Now, we just press STOP on the status bar (Fig. 4)
Fig. 4 Stop on the status bar
After we stopped our macro, how can we run it now? We can go to the Developer tab and press the View Macros command or just click the Alt + F8 key shortcut (Fig. 5)
Fig. 5 View Macros command
In the window that has appeared, we can see all available macros, which are in All Open Workbooks. Now, we have only two. We can see that before the macro name, we have the file name. We can choose macros from many files (Fig. 6)
Fig. 6 File name and files
For us, it’s important to run the Today2 macro, so let’s select it and press the Run button (Fig. 7)
Fig. 7 Run button
Excel has written the TODAY function in our selected cell, which is C5 and has gone to cell A6 (Fig. 8)
Fig. 8 Excel in cell A6
Let’s try a similar thing with the firs macro. Let’s press Alt + F8 shortcut, select the Today2 macro and press RUN. Now, let’s see what exactly our macro has done. Let’s press Alt + F11. We should see our first macro and our new macro Today2, as well as some comments (Fig. 9)
Fig. 9 Our macros
Let’s delete the comments as we don’t need them and let’s locate the lines so that they are clearer to read. Now, we have two lines of the code. The first line of the Today2 macro is very similar to the Today macro. However, instead of ‘Selection’, we have ‘ActiveCell’. It means that our formula is written in the active cell. After the line that contains our macro, Excel will always go to cell A6, We can see it in the next line of ‘Range (“A6”). Select. ‘Select’ means the action, i.e. that we have selected the cell (Fig. 10)
Fig. 10 Code lines
This is how macros are working. If we select a range, the TODAY function will be placed only in the active cell. Then, Excel will go to cell A6.
Let’s try a similar macro. The only difference is that this time we will be using relative references. So let’s do it once again: click on the Record Macro button (1), let’s call it Today3 (2), This Workbook (3) and press OK (4) (Fig. 11)
Fig. 11 Recording a new macro
We’re writing everything once again: TODAY function in cell A7 (1), then Enter (2), then the Stop Recording button (3) (Fig. 12)
Fig. 12 The process of recording
This time we were using relative references. Let’s press Alt + F11. Where is our macro? It’s not in the PERSONAL.XLSB file but in our Macro file, where we record. It means that we have to find Modules (1), where Module 1 should be added (2). Let’s double-click it and we can see our macros (Fig. 13)
Fig. Module 1 with our new macro
We don’t need comments so let’s delete them again. Let’s also adjust the size of the windows so that we can see it clear. We have the TODAY 2 and TODAY 3 functions here. We’ve found our macro (Fig. 14)
Fig. 14 Both macros
There is one more way to find our macros. Let’t go to the Developer (1) tab and go to the View Macros button (2). In the window that appeared we can see that we have many options there like Run, Step into, Edit, Delete and Options (3). For our macro, the Options button is the most significant one, because here we can see shortcuts for our macro (4) (Fig. 15)
Fig. 15 Macro options
If we delete D, this macro will delete the shortcut if I press OK. However, we’re not going to do that. Let’s close the Macro Options window and let’s focus on the Today3 macro. Since this file is still open, we don’t see any names before. Let’s go to the Edit option of this macro (Fig. 16)
Fig. 16 Edit option
This option leads us to the exact window our macro is stored. The first line in the Today3 macro is exactly the same as in Today2 macro. However, the second line is totally different. First of all, both lines start with ‘ActiveCell’. Then, we have Offset (1, 0) — by one row and 0 columns. It means that we went one cell down. Then, VBA tells us that we selected Range A1. In fact, we didn’t select A1 or any other cells. Sometimes, it’s hard to understand VBA due to some inputs. It’s true that we didn’t select A1, but when we went one cell down from the active cell, we selected a range that is the same size as range A1 cell.
Once again. First we start with Active Cell, then there is a dot, which means that we take another step, then choosing the Offset, one row, 0 columns, then we have the Range A1 and what we do with this range, which is selecting the range (Fig. 17)
Fig. 17 Today3 macro
Let’s go back to our worksheet and select cell A8, then go once again to our macro by clicking Alt + F11. This time, we press Play (Run Sub) in our VBA editor or F5 as a shortcut (Fig. 18)
Fig. 18 Run Sub command
What we notice here is that Excel has written the Today function in cell A8 and went one cell below (Fig. 19)
Fig. 19 TODAY function and once cell below
Let’s select a range this time and press F5 (Fig. 20)
Fig. 20 Range selected
What we’re noticing is that the value has been written only in the active cell, although we had selected the whole range. Then, Excel went one cell down (Fig. 21)
Fig. 21 TODAY function and one cell down
Summing up, there is a small difference between relative and absolute references, but still, we have to consider whether we want to use the first one or the second.