arrays - 数组 VBA 中的用户定义对象

标签 arrays vba excel user-defined-types

正如主题行所述,我正在尝试将我写入的类的对象存储到一个数组中。 VBA 给了我一个令人沮丧的错误:

'对象变量或未设置 block 变量'

我很确定我正确地定义了我的对象,并且局部变量显示该对象是我定义的类型并且它的所有字段都已填写,所以我无法弄清楚我的问题出在哪里。

Dim Type1(2 To 250) As myClass
Dim Type2(2 To 250) As myClass
Dim Type3(2 To 250) As myClass
Dim temp_obj As myClass
Dim foo As String

For i = 2 To 250
    Set temp_obj = New myClass
    With temp_obj
        .field1 = Worksheets("Sheet1").Rows(i).Columns(2).Value
        .field2 = Worksheets("Sheet1").Rows(i).Columns(3).Value
        .field3 = Worksheets("sheet1").Rows(i).Columns(4).Value
        .field4 = Worksheets("Sheet1").Rows(i).Columns(5).Value
    End With
    foo = Worksheets("Sheet1").Rows(i).Columns(1).Value
    If foo = "Type1" Then
        Type1(i) = temp_obj
    ElseIf foo = "Type2" Then
        Type2(i) = temp_obj
    ElseIf foo = "Type3" Then
        Type3(i) = temp_obj
    End If
Next i

我的类(class)看起来像这样:
Private pfield1 As Single
Private pfield2 As Integer
Private pfield3 As String
Private pfield4 As String

Public Property Get field1() As Single
    field1 = pfield1 
End Property

Public Property Get field2() As Integer
    field2 = pfield2
End Property

Public Property Get field3() As String
    field3 = pfield3
End Property

Public Property Get field4() As String
    field4 = pfield4
End Property

Public Property Let field1(p As Single)
    pfield1 = p
End Property

Public Property Let field2(p As Integer)
    pfield2 = p
End Property

Public Property Let field3(p As String)
    pfield3 = p
End Property

Public Property Let field4(p As String)
    pfield4 = p
End Property

最佳答案

在底部尝试此更改:

If foo = "Type1" Then
    Set Type1(i) = temp_obj
ElseIf foo = "Type2" Then
    Set Type2(i) = temp_obj
ElseIf foo = "Type3" Then
    Set Type3(i) = temp_obj
End If

关于arrays - 数组 VBA 中的用户定义对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32917623/

相关文章:

javascript - 获取随机范围选择的最大值

arrays - 在 VBA、Excel 中自动创建不同的、可识别的集合

vba - 获取符合条件的所有行并显示在新工作表中

javascript - 如何填写数组中不存在的边界之间的日期?

ios - 具有 Int-s 范围的初始化数组,有人可以解释一下这个单行吗?

javascript - MDN 的 reduce() pollyfill 的 while 循环背后的逻辑

vba - 在幻灯片模式下将 PPT 幻灯片导出为 PDF 时浏览保存位置和命名

Excel VLOOKUP函数源代码

php - 使用 phpexcel 从 mysql 数据库创建 excel 报告

excel - 自定义excel公式函数UDF来计数条件格式