INDEX and MATCH with a function in VBA

Behelith

New Member
Joined
Aug 9, 2019
Messages
10
I'm trying to create a function in VBA to simplify a INDEX and MATCH formula that I use very often.
The INDEX and MATCH formula looks like this: =INDEX(Range1, MATCH(CellToMatch, Range2, 0), 1)
The CellToMatch is allways on the active sheet, Range1 and Range2 are usually on another sheet.
Since this is a function I don't know where the CellToMatch and ranges are.
The selections can be from a range or from a table.

The vba code that I have now is:
Code:
Public Function IndexMatch(CellToMatch As Range, Arr1 As Range, Arr2 As Range)

IndexMatch = Application.WorksheetFunction.Index(Range(Arr1), Application.WorksheetFunction.Match(Range(CellToMatch).Value, Range(Arr2), 0), 1)

End Function

The the function results in a #VALUE !
 

Excel Facts

Last used cell?
Press Ctrl+End to move to what Excel thinks is the last used cell.
Try
Code:
Public Function IndexMatch(CellToMatch As Range, Arr1 As Range, Arr2 As Range)

IndexMatch = Application.Index(Arr1, Application.Match(CellToMatch.Value, Arr2, 0), 1)
End Function
 
Upvote 0
I added IFNA to the function to set the result to "" if the indexmatch function returns an #N/A.
You can replace the "" with Blank if you need a 0 as output for calculations.

Code:
Public Function IndexMatch(CellToMatch As Range, Arr1 As Range, Arr2 As Range)

IndexMatch = Application.IfNa(Application.Index(Arr1, Application.Match(CellToMatch.Value, Arr2, 0), 1), "")

End Function
 
Upvote 0
Rather than using IFNA, you can check if an error is produced like
Code:
Public Function IndexMatch(CellToMatch As Range, Arr1 As Range, Arr2 As Range)

IndexMatch = Application.Index(Arr1, Application.Match(CellToMatch.Value, Arr2, 0), 1)
If IsError(IndexMatch) Then IndexMatch = ""
End Function
 
Upvote 0

Forum statistics

Threads
1,214,590
Messages
6,120,423
Members
448,961
Latest member
nzskater

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top