VB编程:数组中插入新的数组元素
运行效果:
程序代码:
Dim a() As Long
Private Sub Form_Load()
ReDim Preserve a(1 To 4) 'Preserve:当改变原有数组最末维的大小时,使用此关键字可以保持数组中原来的数据。
'Dim i As Long, m As Long
a(1) = 1: a(2) = 2: a(3) = 3: a(4) = 4
For i = 1 To 4
Text1.Text = Text1.Text & "a(" & CStr(i) & ")=" & CStr(a(i)) & "; "
Next i
i = 2
Dim n As Long: n = 6
ReDim Preserve a(1 To 5)
For i = 2 To 5
m = a(i)
a(i) = n
n = m
Next i
For i = 1 To 5
Text2.Text = Text2.Text & "a(" & CStr(i) & ")=" & CStr(a(i)) & "; "
Next i
End Sub
小结:
1、数组中插入新的元素,数组的大小被改变,此时需要使用动态数组,并对数组ReDim重定义
2、Preserve:当改变原有数组最末维的大小时,使用此关键字可以保持数组中原来的数据。