I've replaced the following horrendous Excel formula (values and names have been replaced):
=IF(AND(SourceTable[@Field1]="Value1",SourceTable[@Field2]="Value2"),"Result1",
IF(SourceTable[@Field2]="Value3","Result2",
IF(AND(SourceTable[@Field1]="Value4",SourceTable[@Field3]="Value5"),"Result3",
IF(AND(SourceTable[@Field1]="Value6",OR(SourceTable[@Field3]="Value7",SourceTable[@Field3]="Value8")),"Value9",
VLOOKUP(SourceTable[@Field1];MatchingTable;2;0)))))
With a VBA Function so it would be easier to read and supposedly faster:
Function CUSTOMFUNCTION(oRngField1 As Range, oRngField2 As Range, oRngField3 As Range) As String
'If imbrication
If (oRngField1 = "Value1" And oRngField2 = "Value2") Then
CUSTOMFUNCTION = "Result1"
Exit Function
ElseIf oRngField2 = "Value3" Then
CUSTOMFUNCTION = "Result2"
Exit Function
ElseIf oRngField1 = "Value4" Then
If oRngField3 = "Value5" Then
CUSTOMFUNCTION = "Result3"
Exit Function
ElseIf (oRngField3 = "Value6" Or oRngField3 = "Value7") Then
CUSTOMFUNCTION = "Result4"
Exit Function
End If
End If
'Vlookup if no match before
Dim sTableMatchingFieldLookup As String
Dim sTableMatchingFieldResult As String
sTableMatchingFieldLookup = "MatchingTable[Field1]"
sTableMatchingFieldResult = "MatchingTable[Field2]"
CUSTOMFUNCTION = Range(sTableMatchingFieldResult)(Application.Match(oRngField1, Range(sTableMatchingFieldLookup), 0))
End Function
I get the same result as the function however it does it two times longer than the formula when working with 2k rows. Why isn't the code faster than the Excel formula? Can it be improved? The file is expected to grow so it means the code will be of no use.
Edit: Using more arguments improved the macro, see my response below.