VBA:自定义数据类型和功能(返回值)

时间:2016-09-13 21:43:48

标签: vba function custom-data-type

在测试以下内容时,我在最后一行收到编译错误:(只有在公共对象模块中定义的公共用户定义类型才能被强制转换为变体或从变量强制传递或传递给后期绑定函数。)

Option Explicit

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


Function MakePatterns() As Variant
Dim i As Integer
Dim circles() As aType

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
    Debug.Print circles(i).P_Col; circles(i).P_Rad; _
     circles(i).P_X; circles(i).P_Y
Next
MakePatterns = circles

End Function

有没有办法一起使用TYPE和Function来返回一个数组?或者有更有效的方法吗?

1 个答案:

答案 0 :(得分:1)

在下面的代码 Sub “TestCallFunction”调用功能 “MakePatterns”,然后打印第一个数组从立即窗口中的函数接收回来。

Option Explicit

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


Sub TestCallFunction()

Dim x()                 As aType
Dim i                   As Integer

x = MakePatterns

' print the first result received from Function MakePatterns
Debug.Print x(1).P_Col & ";" & x(1).P_Rad & ";" & x(1).P_X & ";" & x(1).P_Y

End Sub

Public Function MakePatterns() As aType()

Dim i                   As Integer
Dim circles()           As aType

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
    Debug.Print circles(i).P_Col; circles(i).P_Rad; _
    circles(i).P_X; circles(i).P_Y
Next

MakePatterns = circles

End Function