VBA类实例

我在VBA中有一个问题,在每次向该数组添加内容时,数组中的每个项都被replace。

我试图通过给定范围内的行,并将其中的每一行转换为自定义类(在下面的示例中命名为“CustomRow”)。 还有一个pipe理器类(下面称为“CustomRow_Manager”),它包含一个行数组,并且具有添加新行的function。

当第一行添加它工作正常: https : //drive.google.com/file/d/0B6b_N7sDgjmvTmx4NDN3cmtYeGs/view?usp=sharing

但是,当它循环到第二行时,它会replace第一行的内容,并添加第二个条目: https : //drive.google.com/file/d/0B6b_N7sDgjmvNXNLM3FCNUR0VHc/view?usp=sharing

任何想法如何可以解决?

我创build了一些显示问题的代码,在'CustomRow_Manager'类中观察'rowArray'variables

macros档案 https://drive.google.com/file/d/0B6b_N7sDgjmvUXYwNG5YdkoySHc/view?usp=sharing

否则代码如下:

数据

ABC 1 X1 X2 X3 2 xx11 xx12 xx13 3 xx21 xx22 xx23 4 xx31 xx32 xx33 

模块“Module1”

 Public Sub Start() Dim cusRng As Range, row As Range Set cusRng = Range("A1:C4") Dim manager As New CustomRow_Manager Dim index As Integer index = 0 For Each row In cusRng.Rows Dim cusR As New CustomRow Call cusR.SetData(row, index) Call manager.AddRow(cusR) index = index + 1 Next row End Sub 

类模块“CustomRow”

 Dim iOne As String Dim itwo As String Dim ithree As String Dim irowNum As Integer Public Property Get One() As String One = iOne End Property Public Property Let One(Value As String) iOne = Value End Property Public Property Get Two() As String Two = itwo End Property Public Property Let Two(Value As String) itwo = Value End Property Public Property Get Three() As String Three = ithree End Property Public Property Let Three(Value As String) ithree = Value End Property Public Property Get RowNum() As Integer RowNum = irowNum End Property Public Property Let RowNum(Value As Integer) irowNum = Value End Property Public Function SetData(row As Range, i As Integer) One = row.Cells(1, 1).Text Two = row.Cells(1, 2).Text Three = row.Cells(1, 3).Text RowNum = i End Function 

类模块“CustomRow_Manager”

  Dim rowArray(4) As New CustomRow Dim totalRow As Integer Public Function AddRow(r As CustomRow) Set rowArray(totalRow) = r If totalRow > 1 Then MsgBox rowArray(totalRow).One & rowArray(totalRow - 1).One End If totalRow = totalRow + 1 End Function 

你的问题正在使用

 Dim cusR As New CustomRow 

For循环中。 这行实际上只执行一次(注意,当你单步执行代码时,它不会停在那行)

For循环的每个迭代使用相同的cusR实例。 因此,添加到class级的所有manager实例指向相同的cusR

replace这个

 For Each row In cusRng.Rows Dim cusR As New CustomRow 

有了这个

 Dim cusR As CustomRow For Each row In cusRng.Rows Set cusR = New CustomRow 

这明确实例化一个新的类的实例