VBA:使用自定义数据类型和函数返回数组(array(),array())

时间:2016-09-14 16:16:17

标签: arrays vba custom-data-type

这是早期问题的延伸,已得到解答和解决。试图创建一个数组数组并遇到相同的错误"只能强制公共对象模块中的用户定义类型...."

我正在研究使用Collection但尚未想出来。

Option Explicit

Public Type aType
    P_Col As Integer
    P_Rad As Single
    P_X As Single
    P_Y As Single
End Type

Public Type bType
    Shp1() As aType
    Shp2() As aType
    Shp3() As aType
End Type



Function MakePatterns() As bType()
Dim i       As Integer
Dim circles()   As aType
Dim triangles() As aType
Dim squares()   As aType
Dim shps()      As bType


For i = 1 To 5
    ReDim Preserve circles(i)
    circles(i).P_Col = Int(i / 2)
    circles(i).P_Rad = i
    circles(i).P_X = i * 10 + 1
    circles(i).P_Y = i * 10 + 5
Next

For i = 1 To 5
    ReDim Preserve triangles(i)
    triangles(i).P_Col = Int(i / 2)
    triangles(i).P_Rad = i
    triangles(i).P_X = i * 10 + 1
    triangles(i).P_Y = i * 10 + 5
Next

For i = 1 To 5
    ReDim Preserve squares(i)
    squares(i).P_Col = Int(i / 2)
    squares(i).P_Rad = i
    squares(i).P_X = i * 10 + 1
    squares(i).P_Y = i * 10 + 5
Next

For i = 1 To 5
    ReDim Preserve shps(i)
    shps(i) = Array(circles(i), triangles(i), squares(i))
Next

'For i = 1 To 5
'    Debug.Print circles(i).P_Col; circles(i).P_Rad; _
'     circles(i).P_X; circles(i).P_Y
'Next

MakePatterns = shps

End Function

1 个答案:

答案 0 :(得分:0)

因此抛出异常的事情是您使用aType类型的数组作为Shp1,依此类推。稍后,您实现了它,因为它只是一种aType,而不是aType的数组。

现在,根据您的回答,我想出了这段代码。您最终将得到5个bType元素,每个元素包含5个aType元素。但是,你可以根据需要改变它,重点是,你现在有一个bType类型的数组,其中包含aType类型的数组来托管圆形,三角形和正方形。

Option Explicit

Public Type aType
    P_Col As Integer
    P_Rad As Single
    P_X As Single
    P_Y As Single
End Type

Public Type bType
    circles()     As aType
    triangles()   As aType
    squares()     As aType
End Type

Function MakePatterns() As bType()
Dim i, j        As Integer
Dim shps()      As bType


ReDim shps(4)
For i = LBound(shps) To UBound(shps)

      For j = 0 To 4
         ReDim Preserve shps(i).circles(j)
         With shps(i).circles(j)
            .P_Col = Int(j / 2)
            .P_Rad = j
            .P_X = j * 10 + 1
            .P_Y = j * 10 + 5
         End With
      Next j

      For j = 0 To 4
         ReDim Preserve shps(i).triangles(j)
         With shps(i).triangles(j)
            .P_Col = Int(j / 2)
            .P_Rad = j
            .P_X = j * 10 + 1
            .P_Y = j * 10 + 5
         End With
      Next j

      For j = 0 To 4
         ReDim Preserve shps(i).squares(j)
         With shps(i).squares(j)
            .P_Col = Int(j / 2)
            .P_Rad = j
            .P_X = j * 10 + 1
            .P_Y = j * 10 + 5
         End With
      Next j

Next i

MakePatterns = shps

End Function

另外两个提示:

  • 如果您已经知道要包含5个项目,请使用5个项目声明数组,而不是不断调整其大小。
  • 数组的索引从零开始,因此您可能希望将循环更改为For i=0 To 4。否则,您最终会得到bType类型的第一个对象,其中只包含每个属性中值为0的aType项。