VBA中检查枚举值Enum是否为有效值

分类:代码, 博客 标签:

VBA中使用枚举类型Enum时,由于可以把任意的长整形Long数值赋予Enum类型变量,即使这一长整形数值不在相应的Enum类型范围之内,要保证是有效的枚举值,这里水文工具集介绍一个检查枚举值Enum是否为有效值的方法,具体源代码如下:

Option Explicit
'================================
' VBA中检查枚举值Enum是否为有效值
'
' 
'================================
Enum FruitType
    [_First] = 1
    Apple = 1
    Orange = 2
    Plum = 3
    [_Last] = 3
End Enum

Sub TestIsValidEnum()
    Dim N As Long
    Dim IsValid As Boolean
    Dim Fruit As FruitType
    
    Fruit = 1234
    For N = FruitType.[_First] To FruitType.[_Last]
        If Fruit = N Then
            IsValid = True
            Exit For
        End If
    Next

    If IsValid = True Then
        Debug.Print Fruit & " is a valid value for a Fruit."
    Else
        Debug.Print Fruit & " is not a valid value for a Fruit."
    End If
End Sub

这里使用到了一个VBA技巧就是_前缀可以在VBA编辑器中隐藏相应的Enum值,这样下拉列表中不会出现,通过[]使得_前缀命名变成有效名称。



分类:代码, 博客 标签:

2 Responses to “VBA中检查枚举值Enum是否为有效值”

  1. lsc  on 九月 20th, 2010

    VBA强人!

    • CnHUP  on 九月 20th, 2010

      太久没更新,凑个数,进入无米下锅年代了


发表评论

You must be logged in to post a comment.