第1个回答 2008-09-05
'首先,你必须将数组声明为模块级别的变量,例如:
Dim q1() As Long
Private Sub Form_Load()
'此过程中的语句是为了初始化数组
'类似你的 Command1_Click 过程
Command2.Caption = "保存数组": Command3.Caption = "读取数组"
ReDim q1(1 To 10)
For I = LBound(q1) To UBound(q1)
q1(I) = I * 100
Next
End Sub
Private Sub Command2_Click()
'保存数组
Dim F As String, H As Long, I As Long, nStr As String
'要将数组保存为纯文本文件,先将数组转变为字符串
H = UBound(q1)
For I = LBound(q1) To H
nStr = nStr & q1(I)
If I < H Then nStr = nStr & vbCrLf
Next
H = FreeFile
F = "C:\MyText.txt"
Open F For Output As #H '打开文件
Print #H, nStr '将字符串 nStr 保存到文件中
Close #H '关闭文件
End Sub
Private Sub Command3_Click()
'读出数组
Dim F As String, H As Long, I As Long, nStr As String
H = FreeFile
F = "C:\MyText.txt"
ReDim q1(1 To 1) '重定义数组
Open F For Input As #H '打开文件
Do
If EOF(H) Then Exit Do
Input #H, nStr '从文件中读出一行字符串
I = I + 1
ReDim Preserve q1(1 To I)
q1(I) = Val(nStr)
Loop
Close #H '关闭文件
'下面是你显示数组数据的语句
'............
End Sub
'另外,要删除数组中的某项,可以在程序的适当的地方调用下面的过程
'例如,要删除低 2 项,可以加入语句: DelNum 2
Private Sub DelNum(S As Long)
Dim H As Long, I As Long
H = UBound(q1)
If S < 1 Or S > H Then Exit Sub
H = H - 1
For I = S To H
q1(I) = q1(I + 1) '将 S 后面的项目依次上移
Next
If H > 0 Then
ReDim Preserve q1(1 To H)
Else
ReDim q1(1 To 1)
End If
'下面是你显示数组数据的语句
'............
End Sub