I made a custom class and I'm trying to make an array of objects with it but I get an error "Object variable or with block variable not set" when I try to add my object to the array.
Macro :
Option Explicit
Public Function ArrayLen(arr As Variant) As Integer
ArrayLen = UBound(arr) - LBound(arr) + 1
End Function
Function loadRegisteredFood() As ClsRegisteredFood()
' Load all the registered food in memory
Worksheets("Foods").Activate
Dim dataRegisteredFood As Range
Set dataRegisteredFood = Range("RegisteredFoodTable")
Dim registeredFoods() As ClsRegisteredFood
ReDim registeredFoods(dataRegisteredFood.Rows.Count - 1)
Dim x As Integer
For x = 1 To dataRegisteredFood.Rows.Count
Dim registeredFood As New ClsRegisteredFood
registeredFood.Name = dataRegisteredFood.Cells(x, 1).Value
registeredFood.Prot = dataRegisteredFood.Cells(x, 2).Value
registeredFood.Fat = dataRegisteredFood.Cells(x, 3).Value
registeredFood.Carbs = dataRegisteredFood.Cells(x, 4).Value
registeredFood.Netcarbs = dataRegisteredFood.Cells(x, 5).Value
registeredFood.Kcal = dataRegisteredFood.Cells(x, 6).Value
registeredFood.Portion = dataRegisteredFood.Cells(x, 7).Value
registeredFoods(x - 1) = registeredFood
Next x
Dim length As Integer
length = ArrayLen(registeredFoods)
MsgBox length
Dim rf As Variant
For Each rf In registeredFoods
MsgBox rf.Name & " contient " & rf.Kcal & " Kcal"
Next rf
loadRegisteredFood = registeredFoods
End Function
Sub test()
Dim registeredFoods() As ClsRegisteredFood
registeredFoods = loadRegisteredFood()
' printRegisteredFood (registeredFoods)
End Sub
Class :
Public Name As String
Public Prot As Double
Public Fat As Double
Public Carbs As Double
Public Netcarbs As Double
Public Kcal As Double
Public Portion As String
The workbook :
https://www.dropbox.com/s/jdoa31jo7f1qz85/test.xlsm?dl=0
The error appear on this line registeredFoods(x - 1) = registeredFood
What could be causing this?
Thanks.
Setthe array itemsSet registeredFoods(x - 1) = registeredFood.