Search code examples
excelvba

Object variable or With Block variable not set passing a class instance to a method


I am having the following error in VBA (excel):

Object variable or With Block variable not set

The error happens on the line I have annotated in the following piece of code:

 Dim todoItemInstance As TodoItem
 Set todoItemInstance = New TodoItem
 todoItemInstance.title = title
 todoItemInstance.status = status
 todoItemInstance.description = description
  
 Dim projectInstance As project
 Set projectInstance = New project
 If parentTask <> "" Then
    projectInstance.name = parentTask
    projectInstance.AddItem todoItemInstance '<== Error happens here!
     
    If Not projects.Exists(parentTask) Then
        projects.Add parentTask, projectInstance
    End If
'snip....

Project and TodoItem are two classes I defined. Here are their ClassModules:

Project

Public name As String
Private Items() As TodoItem
Private count As Integer
Private size As Integer

Private Sub Class_Initialize()
    Debug.Print "New Project created"
    count = 0
    size = 3
    ReDim Items(size)
End Sub

Private Sub resize()
    size = size * 2
    ReDim Preserve Items(size)
End Sub

Public Sub AddItem(item As TodoItem)
    If count = size Then
        resize
    End If
    
    Items(count) = item
    count = count + 1
End Sub

TodoItem

Public title As String
Public status As String
Public description As String

Solution

  • The error is not thrown on that line, it's thrown on

    Items(count) = item
    

    Items is an array of objects so you need to have

    Set Items(count) = item