arrays - VBA 中二维数组中的一个数组元素的具体引用

标签 arrays vba reference

我想要对二维数组中的一个元素进行引用,如下所示:

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

我可以这样写吗:?

    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) 的引用,并且我可以访问第二个维度中的所有元素。

这可能是错误的还是完全错误的?

编辑:

我会给出:

1.: Mike -> arr(0,0)
2.: Ipod -> arr(1,1)
3.: .... -> arr(2,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

关于arrays - VBA 中二维数组中的一个数组元素的具体引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17083453/

相关文章:

vba - VBA.CBlah 和 CBlah 的区别

vba - 将所有命名范围提取到一个类中

java - 是否可以在 Java 中对两个字符串数组使用一个 for 循环?

Java:使用外部参数对数组进行排序

excel - 检查剪贴板是否为图像

c++ - 默认编译器生成引用运算符(在 C++ 中)?

c++ - 用类实例的指针初始化是C++中唯一的吗?

C++类与函数,构造函数中的引用参数

arrays - 类型 '[Double]?' 的值没有成员 'append'

ios - 对数组进行排序,其中包含日期,月份