1. 声明和初始化二维数组:
Dim myArray(1 To 3, 1 To 4) As Integer '声明一个3行4列的整数二维数组
'给数组赋值
myArray(1, 1) = 10
myArray(1, 2) = 20
myArray(1, 3) = 30
myArray(1, 4) = 40
myArray(2, 1) = 50
myArray(2, 2) = 60
myArray(2, 3) = 70
myArray(2, 4) = 80
myArray(3, 1) = 90
myArray(3, 2) = 100
myArray(3, 3) = 110
myArray(3, 4) = 120
2. 访问二维数组元素:
MsgBox myArray(2, 3) '将显示70,表示第2行第3列的元素
3. 使用嵌套循环处理二维数组:
Dim i As Integer
Dim j As Integer
For i = 1 To 3
For j = 1 To 4
MsgBox myArray(i, j)
Next j
Next i
4. 动态声明二维数组:
Dim rows As Integer
Dim cols As Integer
rows = 3
cols = 4
Dim dynamicArray() As Integer
ReDim dynamicArray(1 To rows, 1 To cols)
'给动态数组赋值
dynamicArray(1, 1) = 10
dynamicArray(1, 2) = 20
'...
'访问动态数组元素
MsgBox dynamicArray(2, 3)
这些示例演示了如何声明、初始化和访问二维数组。二维数组在处理表格状数据时非常有用,可以通过嵌套循环迭代数组的每个元素。
转载请注明出处:http://www.zyzy.cn/article/detail/6693/VBA