一维数组
' 固定长度一维数组
Sub Array1_Sub()
' 定义一维数组
Dim TestArray(1 To 4) As Integer, Num As Integer
TestArray(1) = 101
TestArray(2) = 102
TestArray(3) = 103
TestArray(4) = 104
' 指定长度遍历。缺点:有输入错误越界风险
For Num = 1 To 4
MsgBox "(1)Num值:" & Num & " 对应数组索引值:" & TestArray(Num)
Next Num
' 自动使用最大最小长度遍历
For Num = LBound(TestArray) To UBound(TestArray)
MsgBox "(2)Num值:" & Num & " 对应数组索引值:" & TestArray(Num)
Next Num
End Sub
二维数组
' 固定长度二维数组
Sub Array2_Sub()
Dim TestArray(1 To 2, 1 To 4) As Integer, Row As Integer, Col As Integer
TestArray(1, 1) = 11
TestArray(1, 2) = 12
TestArray(1, 3) = 13
TestArray(1, 4) = 14
TestArray(2, 1) = 21
TestArray(2, 2) = 22
TestArray(2, 3) = 23
TestArray(2, 4) = 24
' 指定长度遍历。缺点:有输入错误越界风险
For Row = 1 To 2
For Col = 1 To 4
MsgBox "行:" & Row & " 列:" & Col & " 值:" & TestArray(Row, Col)
Next Col
Next Row
' 自动使用最大最小长度遍历
For Row = LBound(TestArray, 1) To UBound(TestArray, 1)
For Col = LBound(TestArray, 2) To UBound(TestArray, 2)
MsgBox "行:" & Row & " 列:" & Col & " 值:" & TestArray(Row, Col)
Next Col
Next Row
End Sub
动态长度数组
' 动态长度数组
Sub ArrayDynamic_Sub()
' 定义一维动态数组
Dim TestArray() As Integer, Num As Integer
' 设置一维动态数组大小
ReDim TestArray(1 To 4)
TestArray(1) = 101
TestArray(2) = 102
TestArray(3) = 103
TestArray(4) = 104
' 自动使用最大最小长度遍历
For Num = LBound(TestArray) To UBound(TestArray)
MsgBox "Num值:" & Num & " 对应数组索引值:" & TestArray(Num)
Next Num
' 设置一维动态数组大小(不保留之前的数据)
'ReDim TestArray(1 To 3)
' 设置一维动态数组大小(保留之前的数据)
ReDim Preserve TestArray(1 To 5)
TestArray(5) = 105
' 自动使用最大最小长度遍历
For Num = LBound(TestArray) To UBound(TestArray)
MsgBox "New Num值:" & Num & " 对应数组索引值:" & TestArray(Num)
Next Num
End Sub
关注
笔者 - jxd