文本文件格式如下:
125
fdf
548
4t5
4555
d
48
要求,把文件中符合000--999的字符串存到一个数组里,数组的长度由符合条件的字符串个数决定,其他不符合条件如字母,小于3个或大于3个的字符串都忽略掉.
125
fdf
548
4t5
4555
d
48
要求,把文件中符合000--999的字符串存到一个数组里,数组的长度由符合条件的字符串个数决定,其他不符合条件如字母,小于3个或大于3个的字符串都忽略掉.
i=1
open "文件路径及名称" for input As #1
Line Input #1, Temp
if Temp<"000" And Temp>"999" then
redim Preserve arrResult(i)
i=i+1
End if
Close #1
i=1
open "文件路径及名称" for input As #1
Line Input #1, Temp
if Temp>="000" And Temp<="999" then
redim Preserve arrResult(i)
i=i+1
End if
Close #1
Dim filestring As String, arrResult() As String, i As Integer, linestring As String
filestring = App.Path & "\a.txt"
Dim ofs As FileSystemObject
Set ofs = New FileSystemObject
Dim txtStream As TextStream
Set txtStream = ofs.OpenTextFile(filestring) '打开文件
i = 1Do Until txtStream.AtEndOfStream '按行读出
linestring = txtStream.ReadLine
If IsNumeric(linestring) = True And (Asc(linestring) >= Asc("000") And Asc (linestring) <= Asc("999")) Then '判断条件
ReDim Preserve arrResult(1 To i) As String '扩大数组
arrResult(i) = linestring '写入数组
i = i + 1
End If
Loop
txtStream.Close ‘关闭流
Set ofs = Nothing ‘关闭对象
Exit SubEnd Sub
这个条件是不是不对呀,我按你的方法,结果把小于3位的大于3位的都读了进去,只过滤掉了字母
linestring = txtStream.ReadLine
If IsNumeric(linestring) = True And Len(linestring) = 3 Then
If CInt(linestring) >= 0 And CInt(linestring) <= 999 Then
ReDim Preserve arrResult(1 To i) As String
arrResult(i) = linestring
i = i + 1
End If
End If
Loop这样选出来的结果是 125,548
IsNumeric(linestring) = True '删除包含字母的
len(linestring) = 3 '显示三位字符串
如果想写入另一个文本文件,步骤如下
1.写入已存在文本文件还是自己创建 (指定路径)
2.打开目标文本文件成写入状态
3.对数组作循环,逐条写入
4.关闭文件具体代码可以自己试探着来。当你定义了 FileSystemObject,很多的函数都可以看到了。
自己写完了代码才可以真正的懂
Private Sub Command1_Click() 'read
num = 0
Open "c:\xxx.txt" For Input As #1
Do While Not EOF(1)
Line Input #1, Temp
If IsNumeric(Temp) And Len(Temp) = 3 And Temp > "0" Then
num = num + 1
ReDim Preserve x(1 To num)
x(num) = Temp
End If
Loop
Close #1
End SubPrivate Sub Command2_Click() 'write
Open "c:\newfile.txt" For Output As #1
Print #1, , Join(x, vbCrLf)
Close #1
End Sub
Private Sub Command1_Click() 'read
Dim y() As String, i As Integer
Open "c:\xxx.txt" For Binary As #1
Temp = Space(LOF(1))
Get #1, , Temp
Close #1
y = Split(Temp, vbCrLf)
For i = 0 To UBound(y)
Temp = y(i)
If IsNumeric(Temp) And Len(Temp) = 3 And Temp > "0" Then
num = num + 1
ReDim Preserve x(1 To num)
x(num) = Temp
End If
Next
Close #1
Erase y
End SubPrivate Sub Command2_Click() 'write
Open "c:\newfile.txt" For Binary As #1
Put #1, , Join(x, vbCrLf)
Close #1
End Sub