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

时间:2019-06-07 17:32:49

标签: excel vba

我正在尝试在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/

2 个答案:

答案 0 :(得分:6)

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

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

Dim currentPi As ProgramIncrement
Set currentPi = New ProgramIncrement

Dim处于循环内部没有任何区别-一方面,它使以后重构和提取循环体到其自己的过程范围内变得容易。另一方面, 可以像在每次迭代中创建一个新变量一样被读取,但这不是VBA中作用域的工作方式:最小的作用域是过程作用域-块(例如循环体)不会范围不限。

答案 1 :(得分:-1)

根据Mathieu Guindon的回答,此方法有效。

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