Thursday, March 14, 2013

Excel VBA ternary function

Excel VBA doesn't provide any ternary operator or function. Many a times it will be helpful to have one instead of going with If...else... statement which takes up at least 5 lines. 

So here is how we could create a function to simulate the ternary operator

Public Function iff(condCheck As Boolean, ifTrue As Variant, ifFalse As Variant) As Variant

    If condCheck Then
        iff = ifTrue
    Else
        iff = ifFalse
    End If

End Function


A sample code which uses this function

Dim myStatus as String
'Here we are checking for A2 cell. If it is blank we will assign myStatus with N/A else we will assign it with the cell content

myStatus = iff(ActiveSheet.Range("A2")="","N/A",ActiveSheet.Range("A2"))



1 comment:

  1. Wonderful article, thanks for putting this together! This is obviously one great post. Thanks for the valuable information and insights you have so provided here.
    excel vba courses

    ReplyDelete