正确使用布尔/案例?

时间:2018-05-23 22:04:39

标签: vba excel-vba excel

我有问题弄清楚我是否正确编写了这个功能。它将被包含一个字符串,其中包含"%"或者#"#"作为最后一个字符即。 " TA_PQ_SI02 _%&#34 ;.我只想让这个函数告诉我它是%还是#。

我是否以最有效/最恰当的方式做到了这一点?我想不是,也想了解原因。

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

1 个答案:

答案 0 :(得分:2)

当你只想要一个布尔:

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

当你需要第三种可能性时:

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