当我尝试向集合中添加对象时,所有对象值都更改为当前对象,怎么办?

我有一个excel工作簿,我想从“ input1”表中读取列值,并基于列值复制“ input”表中的行,并将其存储在类对象中。对“ input1”表中的所有列条目执行此操作。

Private Sub CommandButton1_Click()
    Call PrepareOutput
End Sub
Public Sub PrepareOutput()
   Dim i,indexValue,inputIndexRow As Integer
   Dim bills As New Collection
   inputIndexRow = 2
   indexValue= Worksheets("Input1").Cells(inputIndexRow,1).Value

   While (Not IsEmpty(indexValue))
      i = indexValue+ 1
      Dim bill As New bill
      bill.quantity = Worksheets("Input1").Cells(inputIndexRow,2).Value
      bill.cost = Worksheets("Input").Cells(i,3).Value
      bills.Add bill
      inputIndexRow = inputIndexRow + 1
      indexValue= Worksheets("Input1").Cells(inputIndexRow,1).Value
   Wend
End Sub

'class Bill has these public variables
Public service As String
Public serialNumber As Byte
Public cost As Double
Public quantity As Byte

当我尝试向集合中添加对象时,所有对象值都更改为当前对象,怎么办?

当我尝试向集合中添加对象时,所有对象值都更改为当前对象,怎么办?

xiaoover 回答:当我尝试向集合中添加对象时,所有对象值都更改为当前对象,怎么办?

您将必须在循环中创建新的Bill实例。您的定义Dim bill As New bill声明了变量bill并创建了一个实例,但是尽管这在循环中,但是它并没有为每次迭代创建一个新的实例。

因此将您的代码更改为

While (Not IsEmpty(indexValue))
    Dim bill As bill
    set bill = new bill
    bill.quantity = Worksheets("Input1").Cells(inputIndexRow,2).Value
    ...
Wend
本文链接:https://www.f2er.com/3161672.html

大家都在问