How to Use Excel VBA to Lookup Value in Range (5 Examples)

Here is a sample video of our work on VBA LOOKUP values in a range in Excel.


How to Open VBA Macro Editor in Excel

VBA is a programming language that may be used for various tasks, and different users can use it. You can launch the VBA editor using the Alt + F11 keyboard shortcut. In the last section, we will generate VBA code that makes it easy to perform Vlookup with multiple criteria in Excel. Therefore, you can follow the simple steps to open the VBA editor.

Steps:

  • Open the Developer tab.
  • Select the Visual Basic command.

Launching Visual Basic Editor from the Developer Tab

  • The Visual Basic window will open.
  • From the Insert option, choose the new Module to enter the VBA code.

Selecting a New Module from the Visual Basic Editor Window


Example 1 – Using the VBA Worksheet Function to Lookup Value in Range with Excel VBA

 

Using Excel VBA WorksheetFunction to Lookup Value in Range

Steps:

  • Enter the following code into the above module.
  • Click on Run to see the output.
Sub Lookup_Value()
Dim ResCell As Range
Dim LookupValCell As Range
Dim LookupVec As Range
Dim ResVec As Range
Set ResCell = Range("G5")
Set LookupValCell = Range("F5")
Set LookupVec = Range("C5:C14")
Set ResVec = Range("D5:D14")
ResCell = WorksheetFunction.Lookup(LookupValCell, LookupVec, ResVec)
End Sub

VBA Breakdown:

  • This code starts with the Sub statement and the name of the subroutine, “Lookup_Value().”
Sub Lookup_Value()
  • Now we are Introducing Variables: The cell where the lookup result will be shown is stored in the variable ResCell As Range. LookupValCell As Range: This variable keeps the lookup value’s cell. LookupVec As Range: This variable stores the lookup vector’s range. ResVec As Range: This variable keeps the result vector’s range.
Dim ResCell As Range
Dim LookupValCell As Range
Dim LookupVec As Range
Dim ResVec As Range
  • The Set command assigns each variable to the appropriate cell or range. The lookup is carried out using the Lookup function. The lookup value is represented by the LookupValCell variable, the lookup vector by the LookupVec variable, and the result vector by the ResVec variable. The ResCell variable holds the lookup’s outcome.
Set ResCell = Range("G5")
Set LookupValCell = Range("F5")
Set LookupVec = Range("C5:C14")
Set ResVec = Range("D5:D14")
ResCell = WorksheetFunction.Lookup(LookupValCell, LookupVec, ResVec)
  • This VBA macro ends with an End statement.
End Sub
			

In the above video, we will demonstrate a data set with some employees’ names, departments, and income. Using the VBA Lookup function, we aim to show the employees’ individual income according to their designation. You can follow the above video to better understand, as it contains all the steps.


Example 2: Using VBA Index Match Application to Lookup Value in Different Columns

 

Using VBA Index Match Application to Lookup Value in Different Columns

Steps:

  • Enter the following code into the above module:
Sub Find_Marks()
Dim studentID As Integer
Dim exam As String
Dim result As Variant
Dim lookupRange As Range
Dim examIndex As Variant
Dim Lookupvalue As Variant
Dim tableArray As Range
'Getting the student ID and exam name from the user
studentID = InputBox("Enter the student ID:")
exam = InputBox("Enter the exam name:")
'Setting the lookup range to be the row of the exam name (B4:F4)
Set lookupRange = Worksheets("Sheet2").Range("B4:F4")
'Finding the column index number of the exam name
examIndex = Application.Match(exam, lookupRange, 0)
'Setting the lookup value to be the student ID
Lookupvalue = studentID
'Setting the table array to be the entire range of data (B4:F7)
Set tableArray = Worksheets("Sheet2").Range("B4:F7")
'Using INDEX to find the student's marks in the exam
result = Application.Index(tableArray, Application.Match(Lookupvalue, tableArray.Columns(1), 0), examIndex)
'Showing the result in a message box
If IsError(result) Then
MsgBox "Error: Student " & studentID & " or exam " & exam & " not found in the table"
Else
MsgBox "Student " & studentID & "'s marks in " & exam & " exam is " & result
End If
End Sub
  • Click on Run to see the output.

VBA Breakdown:

  • This code starts with the Sub statement and the name of the subroutine, “Find_Marks().”
Sub Find_Marks()
  • The code begins by declaring several variables, including studentID, exam, result, lookupRange, examIndex, Lookupvalue, and tableArray. The exam is an integer, while the result is a text (a range).
    Dim studentID As Integer
    Dim exam As String
    Dim result As Variant
    Dim lookupRange As Range
    Dim examIndex As Variant
    Dim Lookupvalue As Variant
    Dim tableArray As Range
  • The user must enter the student ID and exam name into the InputBox function.
    studentID = InputBox("Enter the student ID:")
    exam = InputBox("Enter the exam name:")
  • The lookupRange variable is set to the table row containing the exam names.
    Set lookupRange = Worksheets("Sheet2").Range("B4:F4")
  • The Match function sets the examIndex variable to the provided exam’s column index.
    examIndex = Application.Match(exam, lookupRange, 0)
  • The user-entered student ID is used as the value for the Lookupvalue variable. The full table’s data range is contained in the tableArray variable.
   Lookupvalue = studentID
   Set tableArray = Worksheets("Sheet2").Range("B4:F7")
  • Using the lookupValue and examIndex variables, the Index function searches the table for the student’s grades.
result = Application.Index(tableArray, Application.Match(lookupValue, tableArray.Columns(1), 0), examIndex)
  • This VBA macro ends with an End statement.
End Sub

In the above video, we demonstrated how to use lookup values with a simple macro. We used the INDEX function in VBA to find students’ marks based on the input of student ID and the subject’s name.


Example 3: Using VBA VLookup Function with If Else Statement to Lookup Value in Range in Excel VBA

We will generate the following VBA code in the Module by opening the new Module, which we discussed in the above section on how to launch the VBA macro editor. In this method, we will use the If..Then..Else statement for Excel VBA VLOOKUP in another worksheet.

Using VBA VLookup Function with If Else Statement to Lookup Value in Range in Excel VBA

Steps:

  • Enter the following code into the above Module:
Sub Finding_birthplace()
'Declaring Variables
Dim ws_1 As Worksheet, ws_2 As Worksheet
Dim Finding_birthplaceAs Variant
'Setting sheets in variables
Set ws_1 = Worksheets("Birth_place")
Set ws_2 = Worksheets("VBA")
On Error Resume Next
Finding_birthplace = Application.WorksheetFunction.VLookup(ws_2.Range("B5"), _
ws_1.Range("B5:C11"), 2, False)
On Error GoTo 0
'Using If Else statement
If (IsEmpty(Finding_birthplace)) Then
ws_2.Range("E5").Formula = CVErr(xlErrNA)
Else
ws_2.Range("E5").Value = Finding_birthplace
End If
End Sub
  • Click on Run to see the output.

VBA Breakdown:

Sub Finding_birthplace()
  • Firstly, this VBA  macro begins with the sub-procedure Finding_birthplace, which is used to locate a person’s birthplace by searching for their name in a table.
Dim ws_1 As Worksheet, ws_2 As Worksheet
Dim Finding_birthplaceAs Variant
  • Secondly, we use the Dim statement to declare three variables: ws_1 and ws_2 as Worksheet objects and Finding_birthplace as a Variable data type.
Set ws_1 = Worksheets("Birth_place")
Set ws_2 = Worksheets("VBA")
  • We apply the Set statement to assign the Birth_place and VBA worksheets to the ws_1 and ws_2 variables, respectively.
On Error Resume Next
  • Then, using the On Error Resume Next statement, we ignore any runtime errors that may occur during the macro’s implementation.
 Finding_birthplace = Application.WorksheetFunction.VLookup(ws_2.Range("B5"), _
 ws_1.Range("B5:C11"), 2, False)
  • We set the Finding_birthplace variable to assign the result of the VLOOKUP function, which finds the value in cell B5 of the VBA worksheet in the table in the Birth_place worksheet’s B5:C11 range. The function returns the value in the second column of the table (column C) that corresponds to the matching value in column B.
On Error GoTo 0
  • Here, we apply the, On Error GoTo 0 statement to turn off the error handling.
 If Else statement
           If (IsEmpty(Finding_birthplace)) Then
                  ws_2.Range("E5").Formula = CVErr(xlErrNA)
           Else
                 ws_2.Range("E5").Value = Finding_birthplace
          End If
  • We apply the If Else statement to check if the Finding_birthplace variable is empty. If it is, the code assigns the #N/A error value to cell E5 of the VBA worksheet using the CVErr function. If it is not empty, the code assigns the value of the Finding_birthplace variable to cell E5.
End Sub
  • The Sub procedure ends with the End Sub statement.

In the above video, we will demonstrate a data set with some writers’ names included. We have introduced a Birth Place column to the author lists dataset to show you examples. We aim to find each writer’s birthplace listed in the “Birth_Place” sheet. Our goal is to show the birthplace of each writer using the VBA VLOOKUP. So, you can follow the above video for a better understanding, as it contains all the steps.


Example 4: Using the User-Defined Function to Extract Multiple Matches in Excel VBA

Creating User-Defined Function to Extract Multiple Matches in Excel VBA

Steps:

  • Enter the following code into the above Module. 
Public Function Multiple_Match(ByVal LookupVal As String, ByVal RCell As Range, ByVal Colindex As Integer) As Varian
'Declare local variables
Dim Cell As Range
Dim ResultStr As String
'Use error handling to handle potential errors when accessing cell values
On Error GoTo Correction
'Loop through each cell in the given range.
For Each Cell In RCell
'Check if the cell value matches the lookup value
If Cell.Value = LookupVal Then
'Check if the corresponding column value is not empty
If Cell.Offset(0, Colindex - 1).Value <> "" Then
'Check if the value has not already been included in the result string
If Not Result_String Like "" & Cell.Offset(0, Colindex - 1).Value & "" Then
'Append the value to the result string
ResultStr = ResultStr & ", " & Cell.Offset(0, Colindex - 1).Value
End If
End If
End If
Next Cell
'Remove the leading comma and space from the result string and return it
Multiple_Match = LTrim(Right(ResultStr, Len(ResultStr) - 1))
Exit Function
'Label to jump to in case of an error
Correction:
'Return an empty string if an error occurs.
Multiple_Match = ""
End Function
  • Click on Run to see the output.

VBA Breakdown:

  • This code creates a VBA method called Multiple_Match that accepts three arguments: Colindex, LookupVal, and RCell. (an integer). A comma-separated list of values in the column designated by the Colindex will be returned after this function has searched for instances of the LookupVal within the RCell range.
Public Function Multiple_Match(ByVal LookupVal As String, ByVal RCell As Range, ByVal Colindex As Integer) As Variant
  • Cell (a range) and ResultStr (a string) are declared as local variables. Then, it configures error handling to detect any mistakes that might happen when accessing cell values.
Dim Cell As Range
Dim ResultStr As String
On Error GoTo Correction
  • The code then uses a For Each loop to iterate through each cell in the RCell range.
For Each Cell In RCell
  • It determines whether the value in each cell corresponds to the LookupVal. The function determines whether the relevant column value (defined by the Colindex) is not empty if the value in the cell matches the LookupVal. The function checks to see if the value hasn’t previously been used in the ResultStr if the column value isn’t empty. The function appends the value to the ResultStr string variable if it hasn’t already been there. Otherwise, it removes it.
  If Cell.Value = LookupVal Then
            If Cell.Offset(0, Colindex - 1).Value <> "" Then
                If Not Result_String Like "" & Cell.Offset(0, Colindex - 1).Value & "" Then
                ResultStr = ResultStr & ", " & Cell.Offset(0, Colindex - 1).Value
                End If
            End If
        End If
    Next Cell
  • The function checks every cell in the RCell range before removing the leading comma and space from the ResultStr and returning it as the function’s output value.
Multiple_Match = LTrim(Right(ResultStr, Len(ResultStr) - 1))
Exit Function
  • If an error occurs while the function is being executed, the output value is set to an empty string, and the error handling jumps to the Correction label.
Correction:
Multiple_Match = ""
End Function

We have created a User-Defined function named Multiple_Match, which allows you to extract multiple matches of sold products for different people.


Example 5: Creating a UserForm to Lookup Value in Range with Excel VBA

Creating an UserForm in VBA Macro

Steps:

  • Open the VBA Editor.
  • Select the Insert option.
  • Click the UserForm.

Creating an UserForm to Lookup Value in Range with Excel VBA

  • Enter the following code into the above module:
Private Sub ComboBox1_Change()
'Declaring variable
Dim i
'Applying COUNTA function
i = Application.WorksheetFunction.CountA(Sheet2.Range("B:B"))
'Using Fir loop
For j = 1 To 4
Me("Textbox" & j).Value = Application.WorksheetFunction.VLookup(Me.ComboBox1.Value, _
ActiveSheet.Range("B" & 2, "F" & i), j + 1, 0)
Next j
End Sub
Private Sub UserForm_Initialize()
Me.ComboBox1.RowSource = "Name"
End Sub
  • Click on Run to see the output.

VBA Breakdown:

Private Sub ComboBox1_Change()
'Declaring Variable
Dim i
'Using CountA worksheet function
i = Application.WorksheetFunction.CountA(ActiveSheet.Range("B:B"))
  • We define the first subprocedure, “ComboBox1_Change()”. Secondly, we declare a variable “i“. Then, it counts the number of cells that contain data in column B of ActiveSheet using the COUNTA worksheet function and assigns the value to “i“.
For j = 1 To 4
  Me("Textbox" & j).Value = Application.WorksheetFunction.VLookup(Me.ComboBox1.Value, Sheet2.Range("B" & 2, "F" & i), j + 1, 0)
Next j
  • The For loop runs for four iterations. Each iteration uses the VLOOKUP function to look up the selected name in the data range. It returns the column value corresponding to the current iteration plus one (starting with column C). The value is then assigned to the corresponding TextBox (named “Textbox1” to “Textbox4“).
  • Private Sub UserForm_Initialize()
    Me.ComboBox1.RowSource = "Name"

    We will define a sub-procedure “UserForm_Initialize()“.

  • It sets the RowSource property of the ComboBox to “Name“, which means that the ComboBox gets its list of names from a named range called “Name“.
End Sub
  • This VBA macro ends with an End statement.

We created a UserForm that contains a Combo Box and four Text Boxes. The Combo Box lists names, and when a name is selected, the Text Boxes display information associated with the name from a worksheet named “Sheet2.” The VLOOKUP function looks up all the information with the selected name as the lookup value, and the data ranges from column B to column F. For better understanding, follow the video above, showing the detailed process.


Things To Remember

  • A substitute for VLOOKUP is the LOOKUP function.
  • The result column does not always need to be to the right of the lookup value to use the LOOKUP function.
  • The lookup and result vectors should have the same range length.
  • More crucially, the VLOOKUP function requires we provide a column index number.

Download the Practice Workbook


<< Go Back to Lookup | Formula List | Learn Excel

Get FREE Advanced Excel Exercises with Solutions!
Bishawajit Chakraborty
Bishawajit Chakraborty

Bishawajit Chakraborty, a Rajshahi University of Engineering & Technology graduate with a B.Sc. in Mechanical Engineering, has been associated with ExcelDemy since 2022. Presently, he is a content developer, specializing in Excel Power Query, Data Analysis and VBA. It is worth mentioning that he has authored more than 90 articles on VBA content development. His profound interest lies in the fields of data analytics and data science. He possesses expertise in VBA, Power BI, machine learning, and Python... Read Full Bio

2 Comments
  1. Hi Bishawajit
    This is useful function up until now.
    “=LOOKUP(2,1/($A$2:$A$19=D2),$B$2:$B$19)”

    However, I am looking for a function or formula that can be added.
    This is to look up only a cell with value (ignoring or skipping all with any blank cell from bottom to top row).

    Thanks for your great help.

    Regards,
    Nats

    • Reply Lutfor Rahman Shimanto
      Lutfor Rahman Shimanto Sep 26, 2023 at 12:15 PM

      Hello NATS CO

      Thanks for reaching out and posting your comment. You have given us wonderful advice, which is very appreciated. You want to modify the existing formula you have given in such a way that it will look up only a cell with value and ignore all blank cells from bottom to top.

      I am delighted to inform you that I have developed such a formula by modifying your given formula. I have also developed a User-defined function using Excel VBA.

      Modified Excel Formula:

      =LOOKUP(2,1/(FILTER($C$5:$C$14,$C$5:$C$14<>“”)=F5),$D$5:$D$14)

      Excel VBA User-defined Function:
      Open the VBA Editor => Paste the following code in a module => Save.

      
      Function CustomLookupNonBlank(FindValue As Variant, LookupRange As Range, MatchRange As Range) As Variant
          
          Dim i As Long
          
          For i = LookupRange.Cells.Count To 1 Step -1
              If Not IsEmpty(LookupRange.Cells(i).Value) And LookupRange.Cells(i).Value = FindValue Then
                  CustomLookupNonBlank = MatchRange.Cells(i).Value
                  Exit Function
              End If
          Next i
          
          CustomLookupNonBlank = CVErr(xlErrNA)
      
      End Function
      

      Return to the sheet => Use the user-defined function like other worksheet functions.

      I hope the idea will fulfil your requirements. Good luck!

      Regards
      Lutfor Rahman Shimanto

Leave a reply

Advanced Excel Exercises with Solutions PDF

 

 

ExcelDemy
Logo