2

次のような 2 次元配列の 1 つの要素を参照したい:

    dim ary(5,5) as String 
    ary(1) = "Michael, Thomas, Bill, Mike, Pascal"
    ary(2) = "Iphone,HTCOne,SGS4,SGS3"
    '... and so on

私はこのようにsthを書くことができます:?

    For i = 0 To UBound(ary)
            activMan = ary(i)
            Sheets("Example").Cells(1,1) = activMan(i)
            'activMan is now Michael
            ' so i dont have to use two variables...
        End If
    Next i
    ' in the next round activMan is going to be HTCOne

これで、activMan は最初の次元の ary(i) の参照になり、i は 2 番目の次元のすべての要素にアクセスできるようになります。

それは可能ですか、それとも完全に間違っていますか?

編集:

私は配ります:

1.: Mike -> arr(0,0)
2.: Ipod -> arr(1,1)
3.: .... -> arr(2,2)

しかし、私はそれが1つの変数だけで可能であることに気付きました...^^

4

1 に答える 1

2

それは完全に間違っています:p

このつぼみを分析してください:)

Option Explicit

Sub build2DArray()
    ' 2D 5 element array
    ' elements  1st  2nd   3rd   4th   5th
    ' index 0 [0, 0][1, 0][2, 0][3, 0][4, 0]
    ' index 1 [0, 1][1, 1][2, 1][3, 1][4, 1]

    Dim arr(0 To 5, 0 To 1) as String  ' same as Dim arr(5, 1) 

    arr(0, 0) = "Mike"
    arr(1, 0) = "Tom"
    arr(2, 0) = "Bill"
    arr(3, 0) = "Michael"
    arr(4, 0) = "Pascal"

    arr(0, 1) = "IPhone"
    arr(1, 1) = "Ipod"
    arr(2, 1) = "Mac"
    arr(3, 1) = "ITunes"
    arr(4, 1) = "IArray"

    Dim i As Long, j As Long

    Dim activeMan As String
    For i = LBound(arr) To UBound(arr) - 1
        activeMan = arr(i, 0)
        Debug.Print "loop no. " & i & " activeMan: " & activeMan
        Cells(i + 1, 1).Value = activeMan
        Cells(i + 1, 2).Value = arr(i, 1)
    Next i

End Sub

編集:型とカスタム関数を使用して同じ結果を得ることが可能です。見てください

Private Type yourType
tName As String
tPhone As String
End Type

Sub example()
    Dim yType(3) As yourType
    yType(0).tName = "Michael"
    yType(0).tPhone = "iPhone"
    yType(1).tName = "Tom"
    yType(1).tPhone = "Blackberry"
    yType(2).tName = "Dave"
    yType(2).tPhone = "Samsung"

    Dim i&
    For i = LBound(yType) To UBound(yType)
        Debug.Print get_yType(yType, i)
    Next i

End Sub

Private Function get_yType(arr() As yourType, i&) As String
    get_yType = arr(i).tName & " " & arr(i).tPhone
End Function
于 2013-06-13T10:09:15.150 に答える