IFS in VBA (Multiple IF statements)

Copper Contributor

Hey all, I'm trying to define a simple VBA function for quick use in my Excel spreadsheets, but I'm receiving a #VALUE! error. I'm new to Visual Basic and Excel programming, so I'm likely missing something basic. Here is my code.

 

Function Grade(p As Variant) As String
Grade = WorksheetFunction.IFS(p >= 90, "A", p >= 80, "B", p >= 70, "C", p >= 60, "D", p < 60, "F", True, "Error")
End Function

 
The IFS function works perfect with the same parameters in an Excel worksheet. Are my types wrong? I noticed that IFS is not included in the List of worksheet functions available to Visual Basic and I receive a "Sub or function not defined" error if I remove WorksheetFunction. Is there a way to include the IFS function in an Excel VBA module separate from using WorksheetFunction?

Any help would be greatly appreciated.

1 Reply

@Anders_J_Rosen 

Apparently IFS hasn't been added to the WorksheetFunction object. You can use a Select Case block instead:

 

Function Grade(p As Variant) As String
    Select Case p
        Case Is >= 90
            Grade = "A"
        Case Is >= 80
            Grade = "B"
        Case Is >= 70
            Grade = "C"
        Case Is >= 60
            Grade = "D"
        Case Else
            Grade = "F"
    End Select
End Function

or use the LOOKUP function:

Function Grade(p As Variant) As String
    Grade = WorksheetFunction.Lookup(p, Array(0, 60, 70, 80, 90), Array("F", "D", "C", "B", "A"))
End Function