custom if() in vba

lezawang

Well-known Member
Joined
Mar 27, 2016
Messages
1,805
Office Version
  1. 2016
Platform
  1. Windows
Hi I want to create my own if() function so I did the following which did not work. Any idea would be very much appreciated

Function myif(x)

myif = application.IF(x>80,"a",IF(x>60,"b",IF(x>50,"c","f")))

End Function
 

Excel Facts

What do {} around a formula in the formula bar mean?
{Formula} means the formula was entered using Ctrl+Shift+Enter signifying an old-style array formula.
Normally you would do this by using VBA If statement.

Code:
Function myif(x)
    If x > 80 Then
        myif = "a"
    ElseIf x > 60 Then
        myif = "b"
    ElseIf x > 50 Then
        myif = "c"
    Else
        myif = "f"
    End If
End Function

Or Select Case similarly.

However, if you really need one liner, you can use IIf function instead (even readability is really terrible and not preferable):

Code:
Function myif(x)
    myif = IIf(x > 80, "a", IIf(x > 60, "b", IIf(x > 50, "c", "f")))
End Function

Hope it helps.

Suat
 
Upvote 0
another option using case

Code:
Function myif(x)

Select Case x
Case Is > 80
myif = "a"

Case Is > 60
myif = "b"

Case Is > 50
myif = "c"

Case Else
myif = "f"
End Select

End Function


Ross
 
Upvote 0

Forum statistics

Threads
1,224,823
Messages
6,181,180
Members
453,021
Latest member
Justyna P

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