Skip to main content

Kutools for Office — One Suite. Five Tools. Get More Done.

How to calculate median if multiple conditions in Excel?

Author Sun Last modified

Calculating the median of a dataset in Excel is a frequently needed operation in data analysis and reporting. While finding the median for a simple range can be accomplished quickly using standard Excel functions, situations often arise where you need the median value only from data that meets multiple specific criteria—for example, finding the median sales amount for a particular product on a specific date among a large dataset. Handling such complex, conditional operations with traditional functions alone can be challenging. In this tutorial, we’ll introduce various practical solutions to calculate the median with multiple conditions in Excel, exploring both formula-based approaches and automation using VBA for advanced needs.


Calculate median if meets multiple conditions

Suppose you have a data range as shown below, and your task is to determine the median value that meets two criteria: for example, determining the median value of column B where column A has the value "a" and column C has the date "2-Jan". This scenario is especially common in sales reports, class test results, and other business or academic data analysis where filtering by multiple categories is necessary.

a screenshot of the original data

For clarity, let’s prepare the worksheet as follows: In your Excel sheet, enter your conditions and create a layout similar to the below image. Here, column E lists the criteria for column A, and row 1 of columns F and onwards represent the date criteria from column C.

a screenshot of typing new required data

To calculate the median meeting multiple criteria, you can use an array formula that leverages the MEDIAN and IF functions to build a filtered list of values based on your conditions. Here’s how you do it:

1. Click cell F2, where you want the median result to appear, and enter the following formula:

=MEDIAN(IF($A$2:$A$12=$E2,IF($C$2:$C$12=F$1,$B$2:$B$12)))

This formula works by checking, for each row, if the value in column A matches the condition in E2 and if the value in column C matches the header in F1. If both conditions are satisfied, it gathers the value in column B for median calculation.

2. After entering the formula, press Ctrl + Shift + Enter (not just Enter), as this is an array formula. Excel will automatically surround the formula with curly braces { } to indicate an array formula.

3. Drag the fill handle from the bottom right corner of F2 to copy the formula across other relevant cells where you require medians under different conditions, as shown below:

a screenshot of using the formula

Parameter explanations and usage tips: In the formula, $A$2:$A$12 is the range containing the first condition (such as product names), $C$2:$C$12 is the range for the second condition (such as dates), and $B$2:$B$12 is the range containing the numeric values for which you want the median. Adjust these ranges as needed for your own worksheet. Always use absolute references ($ symbols) to ensure ranges do not shift when copying the formula.

Precautions: If no values meet both conditions, the formula will return a #NUM! error. To avoid confusion, you can nest the formula inside IFERROR to return a blank or a custom message:

=IFERROR(MEDIAN(IF($A$2:$A$12=$E2,IF($C$2:$C$12=F$1,$B$2:$B$12))),"No match")

Make sure your data does not contain empty cells or non-numeric values in the median column, as this may also affect results.

This formula-based approach is suitable when you have relatively simple conditions (typically up to two or three criteria). It’s quick to set up and does not require any programming skills. However, for complex filtering with dynamic conditions or larger datasets, maintaining or editing array formulas can become cumbersome.


VBA Code - Calculate median with multiple conditions

For scenarios where you need to automate the conditional median calculation—such as when there are many conditions, large datasets, or the criteria themselves change frequently—a VBA solution can offer a practical alternative. Using VBA, you can build a reusable macro that calculates the median based on any number of conditions. VBA-based solutions are especially useful if you want to streamline repetitive analysis or develop custom Excel processes for reporting and dashboards.

Follow these steps to use VBA for conditional median calculation:

1. Click Developer Tools > Visual Basic. A new Microsoft Visual Basic for Applications window will open. Click Insert > Module, then paste the following code into the Module:

Sub ConditionalMedian()
    Dim DataRange As Range
    Dim CriteriaRange1 As Range
    Dim CriteriaRange2 As Range
    Dim OutputRange As Range
    Dim Criteria1 As Variant
    Dim Criteria2 As Variant
    Dim TempArr() As Double
    Dim i As Long
    Dim j As Long
    Dim count As Long
    
    On Error Resume Next
    xTitleId = "KutoolsforExcel"
    
    Set DataRange = Application.InputBox("Select the range containing median values (e.g., B2:B12):", xTitleId, "", Type:=8)
    Set CriteriaRange1 = Application.InputBox("Select the first criteria range (e.g., A2:A12):", xTitleId, "", Type:=8)
    Criteria1 = Application.InputBox("Enter the first criteria value (e.g., a):", xTitleId, "", Type:=2)
    Set CriteriaRange2 = Application.InputBox("Select the second criteria range (e.g., C2:C12):", xTitleId, "", Type:=8)
    Criteria2 = Application.InputBox("Enter the second criteria value (e.g.,2-Jan):", xTitleId, "", Type:=2)
    Set OutputRange = Application.InputBox("Select the cell to output the result:", xTitleId, "", Type:=8)
    
    count = 0
    For i = 1 To DataRange.Rows.count
        If StrComp(CStr(CriteriaRange1.Cells(i, 1).Value), CStr(Criteria1), vbTextCompare) = 0 And _
           CStr(CriteriaRange2.Cells(i, 1).Value) = CStr(Criteria2) Then
            ReDim Preserve TempArr(count)
            TempArr(count) = DataRange.Cells(i, 1).Value
            count = count + 1
        End If
    Next i
    
    If count = 0 Then
        OutputRange.Value = "No match"
    Else
        Call QuickSort(TempArr, LBound(TempArr), UBound(TempArr))
        If count Mod 2 = 1 Then
            OutputRange.Value = TempArr(count \ 2)
        Else
            OutputRange.Value = (TempArr(count \ 2) + TempArr(count \ 2 - 1)) / 2
        End If
    End If
End Sub

Sub QuickSort(arr() As Double, first As Long, last As Long)
    Dim i As Long
    Dim j As Long
    Dim pivot As Double
    Dim temp As Double
    
    i = first
    j = last
    pivot = arr((first + last) \ 2)
    
    Do While i <= j
        Do While arr(i) < pivot
            i = i + 1
        Loop
        
        Do While arr(j) > pivot
            j = j - 1
        Loop
        
        If i <= j Then
            temp = arr(i)
            arr(i) = arr(j)
            arr(j) = temp
            i = i + 1
            j = j - 1
        End If
    Loop
    
    If first < j Then
        QuickSort arr, first, j
    End If
    
    If i < last Then
        QuickSort arr, i, last
    End If
End Sub

2. Click the Run button button (or press F5) to run the code. You will be prompted to select each of the needed ranges and input your criteria. After completing the prompts, the result (the median that meets all criteria) will be output in the target cell you specified.

This macro allows you to flexibly select the value range, criteria ranges, criteria values, and where to output the result each time it runs. You can also easily adapt the code to include more conditions if needed.

Tips and troubleshooting: When using VBA solutions, ensure that all selected ranges have equal lengths, and criteria match the correct data type and formatting (e.g., text vs. dates). If no value meets the criteria, the output will display "No match." For best stability, save your workbook before running the macro and always enable macros when prompted. This VBA solution is suitable for users familiar with macro security settings and for use in automated Excel workflows.

In summary, the VBA approach automates complex median calculations that are cumbersome or difficult to perform with formulas alone. It is especially well-suited when dealing with variable conditions, frequent recalculations, and large datasets.


Relative Articles:


Best Office Productivity Tools

🤖 Kutools AI Aide: Revolutionize data analysis based on: Intelligent Execution   |  Generate Code  |  Create Custom Formulas  |  Analyze Data and Generate Charts  |  Invoke Kutools Functions
Popular Features: Find, Highlight or Identify Duplicates   |  Delete Blank Rows   |  Combine Columns or Cells without Losing Data   |   Round without Formula ...
Super Lookup: Multiple Criteria VLookup    Multiple Value VLookup  |   VLookup Across Multiple Sheets   |   Fuzzy Lookup ....
Advanced Drop-down List: Quickly Create Drop Down List   |  Dependent Drop Down List   |  Multi-select Drop Down List ....
Column Manager: Add a Specific Number of Columns  |  Move Columns  |  Toggle Visibility Status of Hidden Columns  |  Compare Ranges & Columns ...
Featured Features: Grid Focus   |  Design View   |   Big Formula Bar    Workbook & Sheet Manager   |  Resource Library (Auto Text)   |  Date Picker   |  Combine Worksheets   |  Encrypt/Decrypt Cells    Send Emails by List   |  Super Filter   |   Special Filter (filter bold/italic/strikethrough...) ...
Top 15 Toolsets12 Text Tools (Add Text, Remove Characters, ...)   |   50+ Chart Types (Gantt Chart, ...)   |   40+ Practical Formulas (Calculate age based on birthday, ...)   |   19 Insertion Tools (Insert QR Code, Insert Picture from Path, ...)   |   12 Conversion Tools (Numbers to Words, Currency Conversion, ...)   |   7 Merge & Split Tools (Advanced Combine Rows, Split Cells, ...)   |   ... and more
Use Kutools in your preferred language – supports English, Spanish, German, French, Chinese, and 40+ others!

Supercharge Your Excel Skills with Kutools for Excel, and Experience Efficiency Like Never Before. Kutools for Excel Offers Over 300 Advanced Features to Boost Productivity and Save Time.  Click Here to Get The Feature You Need The Most...


Office Tab Brings Tabbed interface to Office, and Make Your Work Much Easier

  • Enable tabbed editing and reading in Word, Excel, PowerPoint, Publisher, Access, Visio and Project.
  • Open and create multiple documents in new tabs of the same window, rather than in new windows.
  • Increases your productivity by 50%, and reduces hundreds of mouse clicks for you every day!

All Kutools add-ins. One installer

Kutools for Office suite bundles add-ins for Excel, Word, Outlook & PowerPoint plus Office Tab Pro, which is ideal for teams working across Office apps.

Excel Word Outlook Tabs PowerPoint
  • All-in-one suite — Excel, Word, Outlook & PowerPoint add-ins + Office Tab Pro
  • One installer, one license — set up in minutes (MSI-ready)
  • Works better together — streamlined productivity across Office apps
  • 30-day full-featured trial — no registration, no credit card
  • Best value — save vs buying individual add-in