How to Use Excel VBA Index Match with Array (4 Methods)

Dataset Overview

In this guide, we’ll explore four methods for utilizing INDEX and MATCH functions with an array in Excel VBA. To illustrate these techniques, we’ll work with a dataset containing the score distribution of multiple students. The dataset includes their names and scores in subjects such as Physics, Chemistry, and Biology.

Dataset for VBA INDEX MATCH with Array


Method 1 – Using INDEX MATCH for One-Dimensional Array

VBA INDEX MATCH with 1D Array

  • Launch the VBA macro editor from your workbook.
  • Enter the VBA code provided below.
Sub Index_Match_1D_Array()
On Error GoTo Txt
    'variable declaration
    Dim myArr() As Variant
    Dim Name As Range, Physics As Range
    Dim search_name, score As String 
    'set variables
    Set Name = Sheets("Index_Match").Range("B5:B14")
    Set Physics = Sheets("Index_Match").Range("C5:C14")
    'user input
    search_name = InputBox("Physics Score" & vbNewLine & "Enter the name of the student:")
    '1D array formation
    ReDim myArr(1 To 1)
    myArr(1) = search_name
    'show score of the student
    With Application.WorksheetFunction
        score = .index(Physics, .match(myArr(1), Name, 0))
    End With
    MsgBox (myArr(1) & " has scored " & score & " in Physics") 
    Exit Sub
Txt:
    MsgBox "Not Found"
End Sub

VBA Breakdown

Sub Index_Match_1D_Array()
  • This marks the start of a Subroutine called Index_Match_1D_Array.
On Error GoTo Txt
  • This is error-handling statement directs VBA to jump to the Txt label if an error occurs.
    Dim myArr() As Variant
    Dim Name As Range, Physics As Range
    Dim search_name, score As String
  • These are variable declarations: myArr is an array, Name, and Physics are ranges, and search_name and score are strings.
    Set Name = Sheets("Index_Match").Range("B5:B14")
    Set Physics = Sheets("Index_Match").Range("C5:C14")
  • Setting variables: We assign values to Name and Physics based on specific ranges in the worksheet named Index_Match.
    search_name = InputBox("Physics Score" & vbNewLine & "Enter the name of the student:")
  • User input:  The user inputs the name of a student.
    ReDim myArr(1 To 1)
    myArr(1) = search_name
  • 1D array formation:  We create a one-dimensional array called myArr with one element containing the student’s name. 
    With Application.WorksheetFunction
        score = .index(Physics, .match(myArr(1), Name, 0))
    End With
  • Calculating the score: Using the INDEX and MATCH functions, we find the student’s score in Physics.
    MsgBox (myArr(1) & " has scored " & score & " in Physics")
  • Displaying results:  A message box (MsgBox) shows the student’s name and their Physics score.
    Exit Sub
  • This exits the subroutine.
Txt:
    MsgBox "Not Found"
End Sub
  • If an error occurs, this label displays a “Not Found” message.
  • Click the Run button or press F5 to execute the code.
  • In the prompt, put the name of the student and press OK.

InputBox with User Input for 1D Array

To use VBA INDEX MATCH with an array in Excel, enter the student’s name when prompted, and the MsgBox will show their Physics score.

Output MsgBox of 1D array


Method 2 – Use of INDEX MATCH for Two-Dimensional Array

VBA INDEX and MATCH Functions with Two Dimensional Array

  • Open the VBA macro editor in your workbook.
  • Insert the provided VBA code.
Sub Index_Match_2D_Array()
On Error GoTo Txt
    'variable declaration
    Dim myArr(), myArrx(), myArry() As Variant
    Dim myRng As Range, Name As Range
    Dim search_name, search_subject As String
    Set myRng = Sheets("Index_Match").Range("B4:E14")
    Set Name = Sheets("Index_Match").Range("B4:B14")
    '2D array formation
    ReDim myArr(1 To myRng.Rows.Count, 1 To myRng.Columns.Count)
    For I = 1 To myRng.Rows.Count
        For j = 1 To myRng.Columns.Count
            myArr(I, j) = myRng.Cells(I, j)
        Next j
    Next I
    'user input
    search_name = InputBox("Enter the name of the student:")
    search_subject = InputBox("Enter the subject:")
    'look for the subject in 2D array
    For k = 1 To UBound(myArr, 2)
        If myArr(1, k) = search_subject Then
            county = k
        End If
    Next k
    'get 1D array from 2D array
    ReDim myArrx(1 To myRng.Rows.Count)
    For I = 1 To UBound(myArrx)
        myArrx(I) = myArr(I, county)
    Next I
    ReDim myArry(1 To myRng.Rows.Count)
    For I = 1 To UBound(myArry)
        myArry(I) = myArr(I, 1)
    Next I
    'get score of the student
    With Application.WorksheetFunction
        score = .index(myArrx, .match(search_name, myArry, 0))
    End With
    MsgBox ("The score is : " & score)
    Exit Sub
Txt:
    MsgBox "Not Found" 
End Sub

VBA Breakdown

Sub Index_Match_2D_Array()
  • This starts the subroutine.
On Error GoTo Txt
  • Error handling directs VBA to the Txt label if an error occurs.
    Dim myArr(), myArrx(), myArry() As Variant
    Dim myRng As Range, Name As Range
    Dim search_name, search_subject As String
  • Variable declarations: We define arrays myArr, myArrx, and myArry. Also, two Range variables are declared: myRng and Name and String variables are:  search_name and search_subject.
        Set myRng = Sheets("Index_Match").Range("B4:E14")
        Set Name = Sheets("Index_Match").Range("B4:B14")
  • Set ranges: Assign values to myRng and Name.
    ReDim myArr(1 To myRng.Rows.Count, 1 To myRng.Columns.Count)
  • Create a 2D array: Populate myArr with data from the specified range.
    For I = 1 To myRng.Rows.Count
        For j = 1 To myRng.Columns.Count
            myArr(I, j) = myRng.Cells(I, j)
        Next j
    Next I
  • A Nested For Loop goes through each element of the myRng range and puts the value of the cells into the corresponding myArr array element.    
    search_name = InputBox("Enter the name of the student:")
    search_subject = InputBox("Enter the subject:")
  • User input: Prompt the user for the student’s name and subject.
    For k = 1 To UBound(myArr, 2)
        If myArr(1, k) = search_subject Then
            county = k
        End If
    Next k     
  • Another loop – find the subject: locate the subject in the 2D array.
    ReDim myArrx(1 To myRng.Rows.Count)
    For I = 1 To UBound(myArrx)
        myArrx(I) = myArr(I, county)
    Next I

    ReDim myArry(1 To myRng.Rows.Count)

    For I = 1 To UBound(myArry)
        myArry(I) = myArr(I, 1)
    Next I
  • Extract a 1D array: Create myArrx and myArry from the 2D array.
    With Application.WorksheetFunction
        score = .index(myArrx, .match(search_name, myArry, 0))
    End With
  • Get the student’s score: Use INDEX MATCH to find the score.
    MsgBox ("The score is : " & score)
  • Display the result: Show the student’s score in a message box..
    Exit Sub
  • The subroutine is ended using the Exit Sub statement.
Txt:
    MsgBox "Not Found”
End Sub
  • In case of an error, a MsgBox is displayed with the text “Not Found” using the Txt label.
  • Click the Run button or press F5 to execute the code.

Method 3 – Combining INDEX and MATCH Functions for Multiple Criteria with Array

VBA INDEX and MATCH Functions with Multiple Criteria with an Array

  • Open the VBA macro editor in your workbook.
  • Insert the provided VBA code.
Sub Index_Match_Multiple_Criteria()
On Error GoTo Txt
    'variable declaration
    Dim myArr() As Variant
    Dim phy, chem As Integer
    Dim student As String
    Dim Name As Range, Physics As Range, Chemistry As Range
    'set variables
    Set Name = Sheets("Index_Match").Range("B5:B14")
    Set Physics = Sheets("Index_Match").Range("C5:C14")
    Set Chemistry = Sheets("Index_Match").Range("D5:D14")
    'user input
    phy = InputBox("Score in Physics:")
    chem = InputBox("Score in Chemistry:")
    'array formation
    ReDim myArr(1 To 2)
    myArr(1) = phy
    myArr(2) = chem
    'get score of the student
    student = Application.Evaluate("INDEX(" & Name.Address & ", MATCH(1,(" & myArr(1) & "=" & Physics.Address & ")*(" & myArr(2) & "=" & Chemistry.Address & "), 0))")
    MsgBox ("Name of the Student:" & vbNewLine & student)
    Exit Sub
Txt:
    MsgBox "Not Found"
End Sub

VBA Breakdown

Sub Index_Match_Multiple_Criteria()
  • This marks the start of the subroutine.
On Error GoTo Txt
  • Error handling directs VBA to the Txt label if an error occurs.
    Dim myArr() As Variant
    Dim phy, chem As Integer
    Dim student As String
    Dim Name As Range, Physics As Range, Chemistry As Range
  • Variable declarations: We define variables for scores phy and chem, student name, and ranges Name, Physics, and Chemistry.
    Set Name = Sheets("Index_Match").Range("B5:B14")
    Set Physics = Sheets("Index_Match").Range("C5:C14")
    Set Chemistry = Sheets("Index_Match").Range("D5:D14")
  • Set ranges: Assign values to the ranges based on cell locations in the worksheet.
    phy = InputBox("Score in Physics:")
    chem = InputBox("Score in Chemistry:")
  • User input: Prompt the user to enter scores for Physics and Chemistry.
   ReDim myArr(1 To 2)
  • Array formation: Create a two-element array (myArr) with the user-input scores.
    myArr(1) = phy
    myArr(2) = chem
  • The next two lines assign the user-input values of phy and chem to the two elements of myArr.
    student = Application.Evaluate("INDEX(" & Name.Address & ", MATCH(1,(" & myArr(1) & "=" & Physics.Address & ")*(" & myArr(2) & "=" & Chemistry.Address & "), 0))")
  • Get the student’s score: Use INDEX and MATCH functions with multiple criteria.
    MsgBox ("Name of the Student:" & vbNewLine & student)
  • Display the result: Show the student’s name in a message box.
    Exit Sub
Txt:
    MsgBox "Not Found"  
End Sub
  • The last few lines provide an error message if an error occurs during the execution of the code.
  • Click the Run button or press F5 to execute the code.

Read More: VBA INDEX MATCH Based on Multiple Criteria in Excel


Method 4 – Creating a UserForm for INDEX and MATCH Functions with an Array

VBA INDEX and MATCH Functions with Array in a UserForm

  • Open your Excel workbook.
  • Go to Insert > UserForm.

Creating New UserForm

  • From the Toolbox, choose different controls for your UserForm.

Toolbox of UserForm

  • You can insert Labels for instructions and TextBoxes to take user input. Additionally, insert a CommandButton to display the result.

UserForm with ToolBox Controls

  • Double-click on the CommandButton. A new window will open.
  • Enter the following code:
Private Sub CommandButton1_Click()
On Error GoTo Txt
    'variable declaration
    Dim myArr() As Variant
    Dim student As String
    Dim Name As Range, Physics As Range, Biology As Range
    'set variables
    Set Name = Sheets("Index_Match").Range("B5:B14")
    Set Physics = Sheets("Index_Match").Range("C5:C14")
    Set Biology = Sheets("Index_Match").Range("E5:E14")
    'array formation
    ReDim myArr(1 To 2)
    myArr(1) = TextBox1.Value
    myArr(2) = TextBox2.Value
    'get score of the student
    student = Application.Evaluate("INDEX(" & Name.Address & ", MATCH(1,(" & myArr(1) & "=" & Physics.Address & ")*(" & myArr(2) & "=" & Biology.Address & "), 0))")
    MsgBox ("Name of the Student:" & vbNewLine & student)
    Exit Sub
Txt:
    MsgBox "Not Found"
End Sub
  • Run the UserForm. and follow the instructions shown in the video to see the output.

VBA Breakdown

Private Sub CommandButton1_Click()
  • This declares a private subroutine triggered when the user clicks on a command button.
On Error GoTo Txt
  • Error handling directs VBA to the Txt label if an error occurs.
    Dim myArr() As Variant
    Dim student As String
    Dim Name As Range, Physics As Range, Biology As Range
  • Variable declarations: We define variables for the array (myArr), student name (student), and ranges (NamePhysics, and Biology).
    Set Name = Sheets("Index_Match").Range("B5:B14")
    Set Physics = Sheets("Index_Match").Range("C5:C14")
    Set Biology = Sheets("Index_Match").Range("E5:E14")
  • Set ranges: Assign values to the ranges based on cell locations in the worksheet.
    ReDim myArr(1 To 2)
    myArr(1) = TextBox1.Value
    myArr(2) = TextBox2.Value
  • Array formation: Create a dynamic array (myArr) with two elements, using values from TextBoxes.
    student = Application.Evaluate("INDEX(" & Name.Address & ", MATCH(1,(" & myArr(1) & "=" & Physics.Address & ")*(" & myArr(2) & "=" & Biology.Address & "), 0))")
  • Get the student’s score: Use INDEX and MATCH functions with the specified criteria.
    MsgBox ("Name of the Student:" & vbNewLine & student)
  • Display the result: Show the student’s name in a message box.
    Exit Sub
  • This line ends the subroutine.
Txt:
    MsgBox "Not Found"
End Sub
  • This is the error handling section of the code. If there is an error during the execution of the code, it jumps to this section and displays a MsgBox with the text “Not Found“.

How to Use INDEX and MATCH Functions with a Table in Excel VBA

VBA INDEX and MATCH Functions with TableWe’ll use the table below:

VBA INDEX and MATCH Functions with Table

  • Open your Excel workbook.
  • Launch the VBA macro editor.
  • Insert the following code and press the Run button or use the F5 key to execute it:
Sub Index_Match_Table()
On Error GoTo Txt
    'variable declaration
    Dim myTable As ListObject
    Dim Ref As Long
    Dim Output As Variant
    Dim score As Integer
    'set values
    Set myTable = Sheets("Table").ListObjects("Table1") 
    'user input
    score = Int(InputBox("Score in Chemistry:"))
    'get output
    With Application.WorksheetFunction      
        Ref = .match(score, myTable.ListColumns("Chemistry").DataBodyRange, 0)
        Output = .index(myTable.ListColumns("Name").DataBodyRange, Ref)
    End With
    MsgBox (Output & " has got that score")
    Exit Sub  
Txt:
    MsgBox "Not Found"    
End Sub

VBA Breakdown

Sub Index_Match_Table()
  • This marks the start of the subroutine.
On Error GoTo Txt
  • Error handling directs VBA to the Txt label if an error occurs.
    Dim myTable As ListObject
    Dim Ref As Long
    Dim Output As Variant
    Dim score As Integer
  • Variable declarations: We define variables for the table (myTable), row number (Ref), student name (Output), and the user’s input (score).
    Set myTable = Sheets("Table").ListObjects("Table1")
  • Set values: Assign the table reference based on the worksheet and table name.
    score = Int(InputBox("Score in Chemistry:"))
  • User input: Prompt the user to enter the score in chemistry.
    With Application.WorksheetFunction
        Ref = .match(score, myTable.ListColumns("Chemistry").DataBodyRange, 0)
        Output = .index(myTable.ListColumns("Name").DataBodyRange, Ref)
    End With
  • Get the output: Use INDEX and MATCH functions to find the student name.
    MsgBox (Output & " has got that score")
  • Display the result: Show the student’s name in a message box.
    Exit Sub
  • This line indicates that the subroutine has finished executing and exits the subroutine.
Txt:
    MsgBox "Not Found"
End Sub
  • This is a label that is jumped to if an error occurs during the execution of the code. It displays a MsgBox with the text “Not Found“.
  • When prompted, enter the score in chemistry and press OK.

InputBox with User Input in Excel Table

  • You will see a MsgBox showing the name of the student who has the specific score in chemistry.

Output MsgBox


VBA INDEX MATCH for a Different Sheet in Excel

Dataset for VBA INDEX and MATCH Functions with Different Sheets

  • Apply the following VBA code using the INDEX and MATCH functions across different sheets in Excel.

VBA INDEX and MATCH Functions with Different Sheets

Enter the code in your VBA Editor and press the Run button or F5 key to run the code:

Sub Index_Match_Different_Sheets()
On Error GoTo Txt
    'variable declaration
    Dim WS As Worksheet
    Dim search_name, sheet_name, score As String
    'user input
    search_name = InputBox("Total score in 3 subjects" & vbNewLine & "Enter the name of the student:")
    sheet_name = InputBox("Enter the Worksheet name here:")
    Set WS = ThisWorkbook.Sheets(sheet_name)
    'show score of the student from different worksheets
    With Application.WorksheetFunction
        score = .index(WS.Range("D5:D14"), .match(search_name, WS.Range("B5:B14"), 0))
    End With
    MsgBox (search_name & " has scored " & score & " in three subjects")
    Exit Sub
Txt:
    MsgBox "Not Found"
End Sub

VBA Breakdown

Sub Index_Match_Different_Sheets()
  • This is the beginning of the code and the declaration of the subroutine. The name of the subroutine is Index_Match_Different_Sheets.
On Error GoTo Txt
  • This line is used to handle any errors that may occur in the code. If an error is encountered, the code will jump to the label Txt (defined later in the code).
    Dim WS As Worksheet
    Dim search_name, sheet_name, score As String
  • These lines are declaring variables that will be used in the code. WS is declared as a Worksheet object, and search_name, sheet_name, and score are declared as String data types.
    search_name = InputBox("Total score in 3 subjects" & vbNewLine & "Enter the name of the student:")
    sheet_name = InputBox("Enter the Worksheet name here:")
  • These lines prompt the user for input. The first line will display a message in the InputBox asking for the name of a student. The second line will display a message asking for the name of a worksheet.
    Set WS = ThisWorkbook.Sheets(sheet_name)
  • This line sets the variable WS to the worksheet with the name specified by the user input.    
    With Application.WorksheetFunction
        score = .index(WS.Range("D5:D14"), .match(search_name, WS.Range("B5:B14"), 0))
    End With
  • This block of code uses the VBA INDEX MATCH function to find the total score of a student in three subjects. The range D5:D14 contains the scores for each subject, and the range B5:B14 contains the names of the students. The variable search_name is used to find the row number of the student’s name, and the score variable is set to the value in the same row in the range D5:D14.
    MsgBox (search_name & " has scored " & score & " in three subjects")
  • This line displays a MsgBox with the name of the student and their total score in three subjects.  
    Exit Sub
  • This line marks the end of the subroutine and exits the code.
Txt:
    MsgBox "Not Found"     
End Sub
  • This block of code is the error handler that was defined earlier. If an error occurs, the code jumps to this label and displays a MsgBox with the text “Not Found“.

This code allows you to find a student’s total score in three subjects by matching their name across different sheets. If the student’s name is not found, it will display a “Not Found” message.


VBA INDEX MATCH from Another Workbook in Excel

  • Apply the following VBA code using INDEX and MATCH functions across different workbook in Excel VBA. The dataset is the same as the previous one.

VBA INDEX and MATCH Functions with Another Workbook

Enter the following code in your VBA Editor and press the Run button or F5 key to run the code:

Sub Index_Match_Another_Workbook()
On Error GoTo Txt
    'variable declaration
    Dim WB As Workbook
    Dim FilePath As Variant
    Dim WS As Worksheet
    Dim search_name, score As String
    'user input
    search_name = InputBox("Letter Grade " & vbNewLine & "Enter the name of the student:")    
    FilePath = Application.GetOpenFilename("Excel Files (*.xlsx), *.xlsx")
    Set WB = Workbooks.Open(FilePath)
    Set WS = WB.Sheets("Info")
    'show score of the student from another workbook
    With Application.WorksheetFunction
        score = .index(WS.Range("E5:E14"), .match(search_name, WS.Range("B5:B14"), 0))
    End With   
    MsgBox (search_name & " has obtained " & score & " letter grade")
    Exit Sub
Txt:
    MsgBox "Not Found"
End Sub

VBA Breakdown

Sub Index_Match_Another_Workbook()
  • This is the beginning of the code and the declaration of the subroutine. The name of the subroutine is Index_Match_Another_Workbook.
On Error GoTo Txt
  • This line is used to handle any errors that may occur in the code. If an error is encountered, the code will jump to the label Txt (defined later in the code).
    Dim WB As Workbook
    Dim FilePath As Variant
    Dim WS As Worksheet
    Dim search_name, score As String
  • These lines are declaring variables that will be used in the code. WB is declared as a Workbook object, FilePath is declared as a Variant data type, WS is declared as a Worksheet object, and search_name and score are declared as String data types.
    search_name = InputBox("Letter Grade " & vbNewLine & "Enter the name of the student:")
  • This line prompts the user for input. The InputBox will display a message asking for the name of a student.
    FilePath = Application.GetOpenFilename("Excel Files (*.xlsx), *.xlsx")
    Set WB = Workbooks.Open(FilePath)
    Set WS = WB.Sheets("Info")
  • These lines open a dialog box that allows the user to select an Excel file. Once a file is selected, it is assigned to the variable FilePath. The Workbooks.Open method is then used to open the selected file, and the variable WB is set to the opened workbook. Finally, the Sheets method is used to set the variable WS to the worksheet named Info in the opened workbook.
    With Application.WorksheetFunction
        score = .index(WS.Range("E5:E14"), .match(search_name, WS.Range("B5:B14"), 0))
    End With
  • This block of code uses the VBA INDEX MATCH function to find the letter grade of a student. The range E5:E14 contains the letter grades for each student, and the range B5:B14 contains the names of the students. The variable search_name is used to find the row number of the student’s name, and the score variable is set to the value in the same row in the range E5:E14.
  MsgBox (search_name & " has obtained " & score & " letter grade")
  • This line displays a Msgbox with the name of the student and their letter grade.
    Exit Sub
  • This line marks the end of the subroutine and exits the code.
Txt:
    MsgBox "Not Found"
End Sub
  • This block of code is the error handler that was defined earlier. If an error occurs, the code jumps to this label and displays a MsgBox with the text “Not Found“.

This code allows you to find a student’s alpha grade by matching their name across different workbooks. If the student’s name is not found, it will display a “Not Found” message.

Read More: How to Use Excel VBA INDEX MATCH from Another Worksheet


Things to Remember

When using VBA INDEX MATCH based on multiple criteria with an array in Excel, keep the following points in mind:

  1. Assign Lookup Value and Data Array Properly: Ensure that you correctly specify the lookup value and the data array when using INDEX and MATCH functions together.
  2. Use the Application Object: Utilize the Application object to call INDEX and MATCH functions from the worksheet. This ensures consistent behavior and compatibility.
  3. Order Matters: Pay attention to the order of INDEX and MATCH functions. The MATCH function determines the row and column numbers, which the INDEX function uses to retrieve the desired value.
  4. Specify Exact Match: Depending on your requirements, specify whether you want an exact match or allow approximate matches.

Frequently Asked Questions

1. What is the difference between the INDEX and MATCH functions?

  • The INDEX function retrieves a value from a specific row and column within a range of cells or arrays.
  • The MATCH function finds the position of a value in a range of cells or arrays.
  • When used together, MATCH determines the row and column numbers for INDEX to retrieve the desired value.

2. Can I use INDEX and MATCH functions with an array that is not rectangular?

  • Yes, you can use VBA INDEX MATCH with non-rectangular arrays.
  • Ensure that each row in the array has the same number of elements to avoid unexpected results from the MATCH function.

3. How do I handle errors when using INDEX and MATCH functions with an array in Excel VBA?

  • Implement error handling techniques, such as On Error statements, to gracefully handle any issues that may arise when using INDEX and MATCH functions with an array.

Download Practice Workbook

You can download the practice workbooks from here:


 

Get FREE Advanced Excel Exercises with Solutions!
Md. Abu Sina Ibne Albaruni
Md. Abu Sina Ibne Albaruni

Md. Abu Sina Ibne Albaruni holds a BSc in Mechanical Engineering from Bangladesh University of Engineering and Technology. He is a dedicated employee of the ExcelDemy project. He has written quite a large number of articles for ExcelDemy. Besides, he has expertise in VBA. He efficiently automates Excel issues using VBA macros and actively engages in the ExcelDemy forum, offering valuable solutions for user interface challenges. His areas of interest in work and study span MATLAB, Machine Learning,... Read Full Bio

We will be happy to hear your thoughts

Leave a reply

Advanced Excel Exercises with Solutions PDF

 

 

ExcelDemy
Logo