VB数组中插入和删除一个元素

来源:百度知道 编辑:UC知道 时间:2024/09/25 05:57:59
Private Sub Command1_Click() '插入一个元素,J为要插的值,M为要插入的位置,之后输出新的数组,
j = Val(Text1.Text): n = Val(Text2.Text)
Dim x
Dim ib As Integer, ia As Integer
If n < 1 Or n > UBound(a) + 1 Then
x = MsgBox("输入的n不在范围之内", 5 + 48, "输入n的值")
If x <> 4 Then
End
Else
Text2.Text = ""
Text2.SetFocus
End If
Else
Do While ia < n - 1
a(ia) = b(ib): ia = ia + 1: ib = ib + 1
Loop
b(ib) = j
Do While ia >= n - 1 And ia <= UBound(a)
a(ia) = b(ib + 1): ia = ia + 1: ib = ib + 1
Loop
For ib = 0 To UBound(b)
Picture2.Print b(ib);
Next ib

End If
End Sub

Private Sub Command2_Click() '删除一个元素,之后输出新的数组,
Dim x
Dim ic As Integer, ia As Integer
m = Val(Text3.Text)
If m < 1 Or m > UBound(a) + 1 Then
x = MsgBox("输入的m

将数据存在一个动态的数组中(dataArr)

dim dataArr()
dim i as long

1.插入(J为要插的值,M为要插入的位置)
ReDim Preserve dataArr(UBound(dataarr)+1) '将数组放大
for i=UBound(dataarr) to m-1 step -1 '从最下面向m-1循环
dataarr(i)=dataarr(i-1)
next i
dataarr(m)=j

2.删除(M为要删除的位置)
for i=m to UBound(dataarr)-1 '从m向ub..-1
dataarr(i)=dataarr(i+1)
next i
ReDim Preserve dataArr(UBound(dataarr)-1)