Array of class objects as class member in VBA

前端 未结 2 1376
温柔的废话
温柔的废话 2021-01-13 03:37

I\'m writing an Excel macro in VBA to send emails to library patrons alerting them of overdue materials. The data comes from a spreadsheet with data like

Use         


        
相关标签:
2条回答
  • 2021-01-13 04:33

    There's a couple of options.

    The easiest is just to make book_list a Variant type. You can treat it as an array using ReDim. You can use variables of Variant type to store object references just like you would with an object variable.

    The other option is to make book_list a private variable and create accessor methods. This is the preferred way to use classes anyway, and if you're using classes in the first place, you might as well observe good object oriented design. Your class would look something like this.

    Private email_text As String
    ...
    Private book_list() As Book
    
    Private Sub Class_Initialize()
        email_text = "default email text"
        ...
        ReDim book_list(10)
    End Sub
    
    Public Function GetBook(index As Long) As Book
        Set GetBook = book_list(index)
    End Function
    
    Public Sub SetBook(index As Long, b As Book)
        Set book_list(index) = b
    End Sub
    
    0 讨论(0)
  • 2021-01-13 04:34

    Per my comment I would use a collection. Here is how you define it and initialize it

    Public book_list As Collection
    
    'intitalize the collection in the constructor of the class
    Private Sub Class_Initialize()
        Set book_list = New Collection
    End Sub
    

    and to use it

    book_list.Add <book>
    dim bk as Book
    set bk  = book_list.Item(indexNumber)
    
    0 讨论(0)
提交回复
热议问题