gpt4 book ai didi

excel - 为什么 Excel VBA 会覆盖这些对象值

转载 作者:行者123 更新时间:2023-12-04 19:54:04 26 4
gpt4 key购买 nike

我正在尝试在 VBA 中创建一个对象列表,但似乎没有创建新对象,并且正在将值更新为类的单个实例。

这是类

' ---------------------------------------------------------------
'
' Class to represent Program Increment
'
' ---------------------------------------------------------------

Public name As String

Public sprints As New Collection

这是调用代码:

' get the unique pi values
Dim piList As New Collection
For r = firstRow To lastRow
currentVal = Cells(r, 2)
On Error Resume Next
Dim currentPi As New ProgramIncrement
currentPi.name = currentVal
piList.Add currentPi, currentVal
On Error GoTo 0
Next

这是第一个 pi 的输出 enter image description here

这是第二个 pi 的输出 enter image description here

根据诸如此类的在线文档,我没有发现自己做错了什么。 https://analystcave.com/vba-vba-class-tutorial/

最佳答案

As New 创建一个自动实例化的对象。 Dim 语句不可执行,因此确实只有一个对象。

删除 As New 并使用 Set ... = New 语句创建新对象。

Dim currentPi As ProgramIncrement
Set currentPi = New ProgramIncrement

Dim 位于循环内部没有任何区别 - 一方面,它便于以后重构并将循环体提取到其自己的过程范围内;另一方面,它可以被读取,就像在每次迭代时创建一个新变量一样,但这不是范围在 VBA 中的工作方式:最小范围是过程范围 - block (例如循环体)不范围不限。

关于excel - 为什么 Excel VBA 会覆盖这些对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56498916/

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