#How do I describe my Excel VBA code to my students?

Excel VBA is a programming language that allows you to automate tasks in Microsoft Excel. It allows you to write code that can make decisions, loop through data, and perform other actions that would be difficult or time consuming to do manually. It is a powerful tool that can help you save time and increase your productivity.


You can use the following basic syntax to perform a HLOOKUP using VBA:

Sub Hlookup()
    Range("H2").Value = WorksheetFunction.HLookup(Range("G2"),Range("A1:E2"),2,False)
End Sub

This particular example looks up the value in cell G2 in the columns of A1:E2 and finds the value located in the second row of that specific column and then assigns the result to cell H2.

Note: The last argument of False specifies that we want to find an exact match.

The following example shows how to use this syntax in practice.

Example: How to Use HLOOKUP in VBA

Suppose we have the following dataset in Excel that contains information about various basketball players:

Suppose we would like to look up the team name “Mavs” in the dataset and return the corresponding value in the points row.

We can create the following macro to do so:

Sub Hlookup()
    Range("H2").Value = WorksheetFunction.HLookup(Range("G2"),Range("A1:E2"),2,False)
End Sub

When we run this macro, we receive the following output:

The macro correctly returns a value of 22 points for the Mavs.

If we change the name of the team in cell G2 and then run the macro again, it will correctly find the points value for the new team name.

For example, suppose we change the team name to “Rockets” and run the macro again:

Note: You can find the complete documentation for the VBA HLookup method .

x