Excel VBA 在类中声明数组列表

标签 excel vba

我正在尝试创建一个 Staff 类模块,其中包含姓氏等字符串,以及一个用于存储/调用 0-10 个字符串的数组列表,具体取决于使用时添加的数量。

类模块称为 StaffClass 并包含:

Private m_surname As String
Private m_districts as ArrayList

' Surname Prop

Property Get surname() As String
    surname = m_surname
End Property

Property Let surname(surname As String)
    m_surname = Name
End Property

' District Prop
' This is where i'm getting confused

Private Sub Class_ArrList()
    Set m_districts = New ArrayList
End Sub

Property Get districts() As ArrayList
    districts = m_districts
End Property

Property Let districts(districts as ArrayList)
    m_districts = districts    
End Property

主模块包含:

Dim newStaff As StaffClass

Set newStaff = New StaffClass

newStaff.surname = "Smith"

' This is where I want to add to the arraylist

newStaff.districts(0) = "50"

我知道我缺少负载,但正在努力寻找与 VBA 类内的集合相关的很多内容。

希望能帮到你!

最佳答案

您可以将 arraylist 初始化例程放在 Class_Initialize 中,并向该类添加方法来添加/插入/等每个项目。 (或者您可以添加一个方法来将数组列表添加为单个对象)。

此外,由于 ArrayList 是一个对象,因此在检索它时需要使用 Set 关键字。

例如:

类模块

Option Explicit

Private m_surname As String
Private m_districts As ArrayList

' Surname Prop

Property Get surname() As String
    surname = m_surname
End Property

Property Let surname(surname As String)
    m_surname = surname
End Property

Property Get districts() As ArrayList
    Set districts = m_districts
End Property

Function addDistrict(Value As String)
    m_districts.Add Value
End Function

Private Sub Class_Initialize()
    Set m_districts = New ArrayList
End Sub

常规模块

Option Explicit
Sub par()
Dim newStaff As StaffClass
Dim V As ArrayList

Set newStaff = New StaffClass

With newStaff
    .surname = "Smith"
    .addDistrict 50
    .addDistrict "xyz"
End With

Set V = newStaff.districts

Stop
End Sub

关于Excel VBA 在类中声明数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61706647/

相关文章:

arrays - 我可以从 ws.usedrange.value 返回一个以 0 为基数的数组吗?

vba - 在 Excel : how to highlight cells that has a sepcific character more than once

vba - 使用 Excel VBA 时应用程序定义或对象定义的错误

excel - vba,excel - 使用 xls 文件检测其中是否有宏?

vba - 表格内特定范围的填充日期

c# - 从 VBA 访问 .NET 通用对象

c# - 替换excel文件一列中的字符

excel - 为什么 Excel 2010 VBA 用户窗体文本框字体会根据框架大小而变化?

javascript - 如何在客户端读取excel文件内容?

vba - 在 Excel 中将批量文本转换为超链接