【问题标题】:VBA instance item not being changedVBA 实例项未更改
【发布时间】:2017-08-10 19:50:39
【问题描述】:
' CDays
Private pZone As New Collection

Public Property Get Zone() As Collection
    Set Zone = pZone
End Property
Public Property Let Zone(Value As Variant)
    For Each element In Value
        pZone.Add element
    Next
End Property

和子有

' Main Sub
dy.Zone.item("Zone1")(5) = 0

其中 dy 是一个实例 "Zone1" 设置为下面 Item1 的键

dy 实例的结构如下所示

然而,这不会改变 Item(5) 中的值。为什么?

【问题讨论】:

  • 很难将您提供的代码与本地工具窗口屏幕截图相关联。您能否制作一个实际的minimal reproducible example(强调完成)以便我们尝试重现问题?
  • 集合不支持您尝试执行的操作。见:stackoverflow.com/questions/29541710/…
  • 如果您想使用字符串作为键访问项目并编辑项目,您可能需要一个脚本字典

标签: vba excel class


【解决方案1】:

创建将包装将添加到VBA.Collection 的项目的类。然后可以使用集合引用添加/更改此类项目。高温

类Foo

Option Explicit

Private m_id As Integer
Private m_value As String

Public Property Get ID() As Variant
    ID = m_id
End Property

Public Property Let ID(ByVal vNewValue As Variant)
    m_id = vNewValue
End Property

Public Property Get Val() As Variant
    Val = m_value
End Property

Public Property Let Val(ByVal vNewValue As Variant)
    m_value = vNewValue
End Property

模块

Option Explicit

Sub test1()
Dim col As VBA.Collection
Set col = New VBA.Collection

Dim f As Foo
Set f = New Foo
f.ID = 1
f.Val = "AAA"

col.Add f, VBA.CStr(f.ID)

Debug.Print col(f.ID).Val

col(f.ID).Val = "BBB"

Debug.Print col(f.ID).Val

End Sub

输出

AAA
BBB

【讨论】:

    猜你喜欢
    • 2012-11-02
    • 2017-01-02
    • 1970-01-01
    • 1970-01-01
    • 2015-09-13
    • 1970-01-01
    • 2012-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多