VBA 类实例

标签 vba class excel object

我在 VBA 中遇到一个问题,每当我向该数组添加一些内容时,数组中的每个项目都会被替换。

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

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

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

关于如何解决这个问题有什么想法吗?

我创建了一些显示问题的代码,请观察“CustomRow_Manager”类中的“rowArray”变量

宏文件 https://drive.google.com/file/d/0B6b_N7sDgjmvUXYwNG5YdkoySHc/view?usp=sharing

否则代码如下:

数据

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

模块“模块1”

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循环内。该行实际上只执行一次(请注意,当您单步执行 F8 代码时,它不会在此行停止)

For 循环的每次迭代都使用同一个 cusR 实例。因此,添加到类中的所有 manager 实例都指向同一个 cusR

替换这个

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

这显式实例化了该类的一个新实例

关于VBA 类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34217061/

相关文章:

vba - excel中用户窗体的全局工作表变量

android - 从 DB 类或 MVC 中的数据模型类查询数据库?

带有用户提示的 Excel VBA 打印按钮

Excel 搜索公式仅适用于完全匹配

VBA为函数内的单元格赋值?

excel - 如何使用腻子将多个命令传递给 VBA 中的 Shell 函数?

excel - 在 Excel VBA 中使用命名范围获取单元格值

class - 关联/组合关系中有重复的方法

php - Magento 1.7 fatal error : Class 'Mage_Profile_Helper_Data' not found in Mage. php

python - 我不知道为什么我得到一个空白的输出文件