2016-09-13 648 views
1

在测试以下内容时,我在最后一行出现编译错误:(只有在公共对象模块中定义的公共用户定义类型可以强制到变体或从变体或传递到后期绑定功能。)VBA:自定义数据类型和函数(返回值)


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 

是否有使用类型和功能一起返回数组的方法吗?还是有更有效的方法?

+0

对不起,我认为我犯了一个错误函数(作为aType而不是Variant),但只改变了错误类型不匹配。 – user110084

+0

由于您将Type传入或传出函数,因此类对象应该很好用。此外使用Collection而不是数组。 –

+0

@ user110084试试我的答案下面的代码 –

回答

1

在下面“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 
+0

非常感谢谢谢。所以,我在MakePatterns函数中出错: (1)没有声明它Public和 (2)声明它为“aType”,而不是数组“aType()”? – user110084

+0

@ user110084你问你的错误在哪里?请标记为答案 –

+0

@ user110084您需要使用您希望返回的类型声明Function,所以我修改为'Public Function MakePatterns()As aType()' –