Home » excel » vba – Proper use of boolean/case?

vba – Proper use of boolean/case?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m having issues figuring out if I properly wrote this function. It’ll be fed a string that either contains a “%” or a “#” as the last character ie. “TA_PQ_SI02_%”. I just want this function to tell me if it’s a % or #.

Did I do this in the most effiecient/proper way? I think not, and would like to learn why.

Private Function numberOrPercentCheck(ByVal cleanCode As String) As Boolean
    Select Case cleanCode 
        Case Right(cleanCode , 1) = "#"
            numberOrPercentCheck= True
        Case Right(cleanCode , 1) = "%"
            numberOrPercentCheck= False
        Case Else
            Debug.Print "Error: " & cleanCode & " is not formatted properly with a # or % at the end, and has been set to a default #"
            numberOrPercentCheck = True
    End Select
End Function
How to&Answers:

When you just want a Boolean:

Private Function numberOrPercentCheck(ByVal cleanCode As String) As Boolean
    numberOrPercentCheck = Right(cleanCode, 1) = "#"
End Function

When you need a third possibility:

Private Function numberOrPercentCheck(ByVal cleanCode As String) As Variant
    Select Case Right(cleanCode, 1)
        Case "#": numberOrPercentCheck = True
        Case "%": numberOrPercentCheck = False
        Case Else: numberOrPercentCheck = "Error: " & cleanCode & " is not formatted properly with a # or % at the end"
    End Select
End Function