0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

VBAでの2次元配列の初期化方法 3種類 (備忘録)

Posted at

VBAで2次元配列を定義する

中身が所定の値をもつ2次元配列を手っ取り早く定義する方法をまとめてみました。備忘録に

1. For文で定義

まずは、普通にFor文を回す方法。単純に面倒。

case1
Public Sub arrayTest1()
    Dim arr1 As Variant, arr2 As Variant
    Dim i As Long, j As Long
    
    '---- 配列の定義-----
    ReDim arr1(2)
    ReDim arr2(1, 2)
    For i = 0 To 2
        arr1(i) = i + 1
    Next
    
    For i = 0 To 1
        For j = 0 To 2
            arr2(i, j) = j + 3 * i + 1
        Next
    Next
    
    '---- 出力テスト-----
    Debug.Print "arr1の中身"
    For i = LBound(arr1) To UBound(arr1)
        Debug.Print "要素"; i; ":   "; arr1(i)
    Next

    Debug.Print "arr2の中身"
    For i = LBound(arr2) To UBound(arr2)
        For j = LBound(arr2, 2) To UBound(arr2, 2)
            Debug.Print "要素"; i; "-"; j; ":  "; arr2(i, j)
        Next
    Next

    '----- 出力 ----
'    arr1の中身
'    要素 0 :    1
'    要素 1 :    2
'    要素 2 :    3
'    arr2の中身
'    要素 0 - 0 :   1
'    要素 0 - 1 :   2
'    要素 0 - 2 :   3
'    要素 1 - 0 :   4
'    要素 1 - 1 :   5
'    要素 1 - 2 :   6

End Sub

ローカルウィンドウを見ると、下記のような配列ができていることがわかります。
image.png

2. Array関数で定義

1次元ならArray関数で良さそう。2次元以上になると、すこし面倒。

case2
Public Sub arrayTest2()
    Dim arr1 As Variant, arr2 As Variant
    Dim i As Long, j As Long
 
   '---- 配列の定義-----
    arr1 = Array(1, 2, 3)
    arr2 = Array(Array(1, 2, 3), _
            Array(4, 5, 6))

    '---- 出力テスト-----    
    Debug.Print "arr1の中身"
    For i = LBound(arr1) To UBound(arr1)
        Debug.Print "要素"; i; ":   "; arr1(i)
    Next

    Debug.Print "arr2の中身"
    For i = LBound(arr2) To UBound(arr2)
        For j = LBound(arr2(1)) To UBound(arr2(1))
            Debug.Print "要素"; i; "-"; j; ":  "; arr2(i)(j)
        Next
    Next
    
End Sub

あとは、ローカルウィンドウを見ると、出来上がる配列が、For文で作ったときと異なり入れ子?みたいになっている。
image.png

3. 配列リテラルで定義

2次元配列を手軽に定義するなら、一番シンプルに書ける。

case3
Public Sub arrayTest3()
    Dim arr1 As Variant, arr2 As Variant
    Dim i As Long, j As Long

   '---- 配列の定義-----
    arr1 = [{1,2,3}]
    arr2 = [{1,2,3; 4,5,6}]

    '---- 出力テスト-----       
    Debug.Print "arr1の中身"
    For i = LBound(arr1) To UBound(arr1)
        Debug.Print "要素"; i; ":   "; arr1(i)
    Next

    Debug.Print "arr2の中身"
    For i = LBound(arr2) To UBound(arr2)
        For j = LBound(arr2, 2) To UBound(arr2, 2)
            Debug.Print "要素"; i; "-"; j; ":  "; arr2(i, j)
        Next
    Next
    
End Sub

ただし、配列の始まりが0ではなく、1になっていることに注意が必要です。
image.png

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?