VBA中巧用枚举Enum类型模拟集合
VBA中使用集合可以采用Collection,其实我们也可以巧妙运用枚举(Enum)类型来模拟集合(Set),这样可以合并多个枚举(Enum)类型元素来表示用户的多选意图。如下面的例子:
Public Enum FontStyle
Normal = 0
Bold = 1
Italics = 2
Underline = 4
Strikethrough = 8
End Enum
你就可以组合多个值来指定字体的样式。这里一个关键的要求就是枚举里面的指定必须是2的指数倍,这样通过VBA中的位操作”And”操作符我们就可以重新获取各个选项值。如:
'================================
' VBA中巧用枚举Enum类型模拟集合
'
'
'================================
Dim FS As FontStyle
Dim R As Range
Set R = Range("A1")
FS = Bold + Strikethrough + Underline '指定多个字体样式
'检测样式值,抽取各个选项值
If FS And Bold Then
R.Font.Bold = True
End If
If FS And Italics Then
R.Font.Italic = True
End If
If FS And Strikethrough Then
R.Font.Strikethrough = True
End If
If FS And Underline Then
R.Font.Bold = True
End If
当然为了方便我们可以直接使用指数运算来指定各个枚举值,如下:
Public Enum FontStyle
Ex0 = 0
Ex1 = 2 ^ 0
Ex2 = 2 ^ 1
Ex4 = 2 ^ 2
'... as so on to
Ex31 = 2 ^ 31
End Enum
最后,如果是所有集合选项都被选择可以直接令变量的值为-1,因为在位表示上,-1表示Long类型的每一位都是1,同样的,所有集合取消选择可以直接令此变量为0。



iilxy on 十月 6th, 2010
高人,放假都不休息啊
CnHUP on 十月 6th, 2010
太久没耕作,偶尔来撒种
原来L高手也不出去玩啊