我制作了一个自定义类,我试图用它制作一个对象数组 但我得到一个错误"对象变量或没有设置块变量"当我尝试将我的对象添加到数组时。
宏:
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
班级:
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
工作簿:
https://www.dropbox.com/s/jdoa31jo7f1qz85/test.xlsm?dl=0
此行显示错误registeredFoods(x - 1) = registeredFood
导致这种情况的原因是什么?
感谢。
答案 0 :(得分:1)
您遇到的错误是因为Set
中错过了Set registeredFoods(x - 1) = registeredFood
。由于数组是一个对象数组,因此必须使用Set
来设置数组项。
使用Dim registeredFood As New ClsRegisteredFood
registeredFood
时,如果多次调用,则不新创建的ClsRegisteredFood
对象。 Dim
始终只是一个声明。如果registeredFood
不是对象而是Nothing
,它只会创建一个新对象。
Dim registeredFood As New ClsRegisteredFood
与
Dim registeredFood As ClsRegisteredFood
If registeredFood Is Nothing Then Set registeredFood = New ClsRegisteredFood
所以你总是在for循环中覆盖同一个对象。
更改代码如下:
...
Dim x As Integer
Dim registeredFood As ClsRegisteredFood
For x = 1 To dataRegisteredFood.Rows.Count
Set registeredFood = New ClsRegisteredFood
...
Set registeredFoods(x - 1) = registeredFood
Next x
...