Siddharth Rout 会在 cmets 中显示有效点,您最好只使用名称而不是跟踪两个不同的值。
然而,如果您喜欢冒险,您可以创建一个Class Module 来帮助处理这些价值对。如果目标是能够在 Enum 上使用类似于 CallByName 的内容,这将很有帮助。
因此,您可以按照以下方式做一些事情:
eSht1.Properties("FName") ' Returns 1
这比写eSht1.FName 更好吗?使用类,您可以使用 变量 访问值。这使得迭代多个属性或对象变得非常简单。
例如,考虑从this answer 修改以下CEnum 类模块:
Option Explicit
Private pProperties As Object
Public Property Get Properties() As Object
Set Properties = pProperties
End Property
Public Property Let Properties(p As Object)
Set pProperties = p
End Property
Sub Class_Initialize()
Set pProperties = CreateObject("Scripting.Dictionary")
'Add/instantiate your properties here
pProperties("Index") = 0
pProperties("FName") = 0
pProperties("LName") = 0
pProperties("Data1") = 0
pProperties("Data2") = 0
End Sub
使用这个类,我们可以很容易地从任何或所有CEnum 对象中获取属性。
Option Explicit
Sub TestCEnums()
' You can set a CEnum to a variable and instantiate the "properties"
Dim e1 As New CEnum
With e1
.Properties("Index") = 1
.Properties("Data1") = 10
End With
' If you'd prefer to have all of the CEnums in a collection, it might be
' better to add them via a function
Dim enums As New Collection
AddEnum "e2", enums, 11, 12, 13, 14, 15
AddEnum "e3", enums, 22, 23, 24, 25, 26
AddEnum "e4", enums, 99, 88, 77, 66, 55
' Having everything under the dictionary object makes it trivial to get all
' properties from any (or every) CEnum object
Debug.Print "All properties from e1:"
Dim p As Variant
For Each p In e1.Properties.Keys()
Debug.Print p, e1.Properties(p)
Next
enums.Add e1, "e1", "e2" ' Add e1 to the collection
' You can also get only a specific property from all CEnums in a collection
Debug.Print vbCrLf & "The Index property from all CEnums:"
Dim e As CEnum
For Each e In enums
Debug.Print e.Properties("Index")
Next
End Sub
这会产生以下输出:
All properties from e1:
Index 1
FName 0
LName 0
Data1 10
Data2 0
The Index property from all CEnums:
1
11
22
99
这是此示例的 AddEnum 函数:
' Adds a new CEnum to a collection
Private Function AddEnum( _
key As String, _
enums As Collection, _
myIndex As Long, _
myFName As Long, _
myLName As Long, _
myData1 As Long, _
myData2 As Long _
)
Dim tempEnum As New CEnum
With tempEnum
.Properties("Index") = myIndex
.Properties("FName") = myFName
.Properties("LName") = myLName
.Properties("Data1") = myData1
.Properties("Data2") = myData2
End With
enums.Add tempEnum, key
Set tempEnum = Nothing
End Function
编辑
您不仅限于在实际的Properties 属性对象中使用黑客“属性”。 (一点也不混乱!) 例如,如果每个 CEnum 都链接到一个特定的工作表,您可以添加一个带有自己的 Get 和 Let 块的 Sheet 属性。这将允许您向循环添加条件检查。
' SNIP
For Each e In enums
If e.Sheet = someSheet Then
' Do something
End If
Next