gpt4 book ai didi

excel - VBA类模块: get property from an object using another property

转载 作者:行者123 更新时间:2023-12-02 07:36:02 25 4
gpt4 key购买 nike

所有,我正在 VBA 中设置一个类模块结构来添加具有多个里程碑的计划,但我对此还很陌生。我做了以下事情:

  • 名为“Plan”的类模块,包含“name”属性(字符串)和“Milestones”属性(Milestones 类)。
  • 此里程碑类模块是名为“Milestone”的类模块的对象集合。
  • “Milestone”类具有“name”属性和“value”属性。

因此,在我的模块中,我现在指定特定计划的里程碑:

Plan.Milestones.Add "MilestoneA", Cells(i, 5)
Plan.Milestones.Add "MilestoneB", Cells(i, 7)
...

到目前为止一切都很好。现在对于 MilestoneC 我想知道 MilestoneA 的值(value)。如何获取名为“MilestoneA”的里程碑的值。

我知道下面的代码会给我答案,但我不想硬编码“item(1)”(我想使用该名称):

Plan.Milestones.Item(1).Value

在 clsMilestones 类中:

Private prvt_Milestones As New Collection

Property Get Item(Index As Variant) As clsMilestone
Set Item = prvt_Milestones(Index)
End Property

Sub Add(param_Name As String, param_Value As String)

Dim new_milestone As clsMilestone
Set new_milestone = New clsMilestone

new_milestone.Name = param_Name
new_milestone.Value = param_Value

prvt_Milestones.Add new_milestone
End Sub

最佳答案

您的Milestones类是一个集合类。按照惯例,集合类有 Item属性是类的默认成员。您无法轻松地在 VBA 中指定类的默认成员,但这并非不可能。

导出代码文件,在记事本中打开。找到您的Public Property Get Item成员并添加 VB_UserMemId属性 - 当您在那里时,您可以添加 VB_Description属性也是:

Public Property Get Item(ByVal Index As Variant) As Milestone
Attribute Item.VB_UserMemId = 0
Attribute Item.VB_Description = "Gets the item at the specified index, or with the specified name."
Set Item = prvt_Milestones(Index)
End Property

UserMemId = 0是使属性成为类的默认成员的原因 - 请注意,类中只有一个成员可以具有该值。

暂时不要保存并关闭。

您需要让您的集合类与For Each一起工作也循环,要使其工作,您需要 NewEnum返回 IUnknown 的属性,具有许多属性和标志:

Public Property Get NewEnum() As IUnknown
Attribute NewEnum.VB_Description = "Gets an enumerator that iterates through the collection."
Attribute NewEnum.VB_UserMemId = -4
Attribute NewEnum.VB_MemberFlags = "40"
Set NewEnum = prvt_Milestones.[_NewEnum]
End Property

请注意,您的内部封装 Collection有一个名称以下划线开头的隐藏成员 - 这在 VBA 中是非法的,因此要调用它,您需要用方括号将其括起来。

现在这段代码是合法的:

Dim ms As Milestone
For Each ms In Plan.Milestones
Debug.Print ms.Name, ms.Value ', ms.DateDue, ...
Next

保存文件,关闭它,然后将其重新导入到您的项目中。

由于您使用字符串键填充集合(至少您的 Add 方法似乎是这样做的),因此客户端代码可以使用索引或键来检索项目。

现在Item是类的默认成员,现在这是合法的:

Set milestoneA = Plan.Milestones("Milestone A").Value

请注意您的Add方法需要为 Key 指定一个值添加到内部集合时的参数 - 如果您想要由 Name 键控的项目,使用Name作为键:

Public Sub Add(ByVal Name As String, ByVal Value As Variant)
Dim new_milestone As Milestone
Set new_milestone = New Milestone

new_milestone.Name = Name
new_milestone.Value = Value

prvt_Milestones.Add new_milestone, Name
End Sub

关于excel - VBA类模块: get property from an object using another property,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46935206/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com