[VBA]应用 Select Case 语句代替 If 语句

在程序中进行逻辑判断是不可避免的场景,IF语句非常方便地满足了我们的需求,但往往被滥用,过度的IF嵌套使代码的可读性大大降低,尤其是在多次更新而懒于重构代码的情况下。

适当地使用 Select Case 语句代替 IF 语句,可以说是程序员脱离普通的第一步,假设一份代码打开充斥着 IF 语句,那第一反应肯定是“菜鸡”。

Select Case 的结构很简单,如下所示:

Select Case Value
       Case Value1
               Code1
       Case Value2
               Code2
       Case Value3
               Code3
       ……   ……
       Case Else
               Code Else

End Select

这里提供两个示例:

' Example 1

Worksheets("Sheet1").Activate
Select Case ActiveCell.LocationInTable
Case Is = xlRowHeader
    MsgBox "Active cell is part of a row header"
Case Is = xlColumnHeader
    MsgBox "Active cell is part of a column header"
Case Is = xlPageHeader
    MsgBox "Active cell is part of a page header"
Case Is = xlDataHeader
    MsgBox "Active cell is part of a data header"
Case Is = xlRowItem
    MsgBox "Active cell is part of a row item"
Case Is = xlColumnItem
    MsgBox "Active cell is part of a column item"
Case Is = xlPageItem
    MsgBox "Active cell is part of a page item"
Case Is = xlDataItem
    MsgBox "Active cell is part of a data item"
Case Is = xlTableBody
    MsgBox "Active cell is part of the table body"
End Select
' Example 2

Worksheets("Sheet1").Activate
If IsError(ActiveCell.Value) Then
    errval = ActiveCell.Value
    Select Case errval
        Case CVErr(xlErrDiv0)
            MsgBox "#DIV/0! error"
        Case CVErr(xlErrNA)
            MsgBox "#N/A error"
        Case CVErr(xlErrName)
            MsgBox "#NAME? error"
        Case CVErr(xlErrNull)
            MsgBox "#NULL! error"
        Case CVErr(xlErrNum)
            MsgBox "#NUM! error"
        Case CVErr(xlErrRef)
            MsgBox "#REF! error"
        Case CVErr(xlErrValue)
            MsgBox "#VALUE! error"
        Case Else
            MsgBox "This should never happen!!"
    End Select
End If