2016-09-13 16 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 

配列を返すTYPEと一緒に関数を使用する方法はありますか?それとももっと効果的な方法がありますか? 機能「MakePatterns」を呼び出し、それが最初の配列がイミディエイトウィンドウに関数から戻って受信された印刷後サブ「TestCallFunction」以下のコードで

+0

申し訳ありません申し訳ありませんが、(VariantではなくTypeとして)関数内で間違いを犯しましたが、エラーがタイプの不一致に変更されただけです。 – user110084

+0

Typeを関数に渡しているので、クラスオブジェクトを使用するのが良いはずです。さらに、配列の代わりにCollectionを使用します。 –

+0

@ user110084以下の私の答えでコードを試してください –

答えて

1

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

ありがとうShaiありがとう。だから、MakePatterns関数の私の間違いは: (1)パブリック宣言ではなく、 (2)配列 "aType()"ではなく "aType"として宣言していますか? – user110084

+0

@ user110084あなたの間違いはどこにあるのですか? Answer –

+0

@ user110084としてマークしてください。戻りたいタイプの関数を宣言する必要があるので、 'Public Function MakePatterns()AsType()'に変更しました –

関連する問題