2016-12-21 17 views
0

ありがとうございました!EXCEL vbaのユーザー定義型のReDim多次元配列

私の質問は以下の通りです。私はテーブルからデータを取得し、それをユーザー定義型に格納するコードセクションを持っています。テーブルのサイズが変わる可能性があるので、そのタイプの要素に動的にサイズを与えることが考えられます。型は2つの1次元配列と1つの2次元配列を持つ。私は二次元配列に問題があります。 Excel VBAはこの機能をサポートできますか?

Private Type testing_thermo_data 
'one dimesional arrays 
temperature() As Double 
pressure() As Double 
'two dimensional array 
composition() As Double 
End Type 

sub read_from_sheet_to_type() 

Dim data as testing_thermo_data 
Dim a,b,i as integer 
'a and b are determined with some other function (it works), so to simplify I will set them to a number 
a=20 
b=10 
'Now I will reDim the elements of the UDT to the proper size 
'One dimension array with a=10 elements 
ReDim data.temperature (a) as double 
'One dimension array with a=10 elements 
ReDim data.pressure (a) as double 
'Two dimensional array. Matriz of a=10 by b=20 
ReDim data.composition (1 To a, 1 To b) as double 

For i = 0 To (a- 1) 
data.temperature(i) = Application.ActiveSheet.Cells(i + 3, 1).Value 
data.pressure(i) = Application.ActiveSheet.Cells(i + 3, 2).Value 
    For j = 0 To (b-1) 
    'This is the line where my code crashes 
    data.composition(i, j) = Application.ActiveSheet.Cells(i, j + 3).Value 
    Next j 
Next i 
end sub 

$コードを実行すると、次のようなエラーが表示されます。 実行時エラー「1004」: アプリケーション定義またはオブジェクト定義のエラー enter image description here

+1

data.compositionには項目(0,0)があります(1,1)。 –

+0

こんにちはScott Craner、ありがとうございました。あなたが言及したことを試したが、コードは同じことをやっている。まだ動作していません –

+0

Cells()と同じですが、行0にセルがありません –

答えて

0

私はそれを考え出しました。問題は、私がデータを読んでいるところのが番号ではなく一般としてフォーマットされていることでした。それがExcelワークシートからデータを読み取っていない理由です。 これを調べるには、data.composition(i、j)という要素に定数値 "500"を代入してテストしました。私はその仮説を検証するために何をしましたか?

for i=1 To a 
For j = 1 To b 
'This is the line where my code crashes 
data.composition(i, j) = 500 
Next j 
Next i 

問題が特定されたら、私はコードを修正しました。 最終コードの外観は次のとおりです。それは完全に動作します。ご協力いただきありがとうございます!

Option Base 1 
Private Type testing_thermo_data 
'one dimesional arrays 
temperature() As Double 
pressure() As Double 
'two dimensional array 
composition() As Double 
End Type 

sub read_from_sheet_to_type() 

Dim data as testing_thermo_data 
Dim a,b,i as integer 
'a and b are determined with some other function (it works), 
'to simplif I will set them to a number 
a=20 
b=10 
'Now I will reDim the elements of the UDT to the proper size 
'One dimension array with a=10 elements 
ReDim data.temperature (a) as double 
'One dimension array with a=10 elements 
ReDim data.pressure (a) as double 
'Two dimensional array. Matriz of a=10 by b=20 
ReDim data.composition (1 To a, 1 To b) as double 

For i = 1 To (a) 
data.temperature(i) = Application.ActiveSheet.Cells(i + 3, 1).Value 
data.pressure(i) = Application.ActiveSheet.Cells(i + 3, 2).Value 
    For j = 1 To (b) 
    'This is the line where my code crashes 
    data.composition(i, j) = Application.ActiveSheet.Cells(i, j + 3).Value 
    Next j 
Next i 
end sub