2016-09-13 85 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()' –

相關問題