excelvbamatch

Excel VBA Function with Match and Index


I am trying to write a function to use Match and Index to perform a lookup down a column and across two rows for a more complex lookup. I have a spreadsheet where row 3 uses the formula which works but my VBA function is now working as called from row 4. The formula bar is showing C4 passing the parameters. My actual application is more complicated with case conditions with more parameters and the lookup tables will be on various worksheets. I am trying the simple method first. I am wondering if it's a limitation of the Index being used in the VBA.

I added the AddTwoNumbers function just to text and make sure everything was working OK. :)

copy of excel table

Function LookupRate(Code As String, Shift As String, Class As String)

LookupRate = Application.WorksheetFunction.Index(Sheets("Wages").Range("$B$10:$J$12"), WorksheetFunction.Match(Code, Sheets("Wages").Range("$A$10:$A$12"), 0), WorksheetFunction.Match(Shift & Class, Application.WorksheetFunction.Index(Sheets("Wages").Range("$B$9:$J$9") & Sheets("Wages").Range("$B$8:$J$8"), 0), 0))

End Function

Function AddTwoNumbers(Num1 As Long, Num2 As Long)

AddTwoNumbers = Num1 + Num2

End Function

Solution

  • Further to my comment, the VBA version

    Function LookupRate(Code As String, Shift As String, Class As String)
        With Application.WorksheetFunction
            LookupRate = .Index(Sheets("Wages").Range("B10:J12"), .Match(Code, Sheets("Wages").Range("A10:A12"), 0), _
                .Match(Class, Sheets("Wages").Range("B8:J8"), 0) + .Match(Shift, Sheets("Wages").Range("B9:J9"), 0) - 1)
        End With
    End Function
    

    Since you want a unique number returned, you could also use a SUMPRODUCT()- based approach, although I always have to resort to the Evaluate() method in VBA for this, i.e.

    Function LookupRate(Code As String, Shift As String, Class As String)
        SumRate = Worksheets("Wages").Evaluate("=SUMPRODUCT(Wages!B10:J12*(Wages!B8:J8=""" & Class & """)*(Wages!B9:J9=""" & Shift & """)*(Wages!A10:A12=""" & Code & """))")
    End Function