excel - 当我尝试将对象添加到集合中时,所有对象值都更改为当前对象,如何?
问题描述
我有一个 excel 工作簿,我想从“input1”表中读取列值,并根据列值从“输入”表中复制行,并将其存储在类对象中。对“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
解决方案
您必须在循环中创建新的账单实例。您的定义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
推荐阅读
- aem - AEM AUTHOR INSTANCE IS NOT RESPONDING
- c++ - 这里的字符串函数是什么意思
- node.js - 使用 LuisRecognizer 模拟 LUIS 响应不起作用
- javascript - angular Location.onUrlChange 如何正确退订
- wordpress - 搜索中的分类过滤器不显示分配的帖子
- ios - 为 Facebook SDK 将 Graph API 从 Swift 3 转换为 Swift 5
- node.js - docker RUN/CMD 可能未执行
- highcharts - 在 highchart 的顶部和底部显示 stackLabels
- c++ - 在 Visual Studio Code C++ 调试器中设置断点时出错
- javascript - 如何设置 ChartJS 动画速度?