读TXT文件行数出错,请问哪里错了?
从网上找到如下一段程序,说是对TXT文件在内存中读写,我用一个TXT文件试了试,发现报“实时错误9 下标越界”错误,我分步运行,发现For I = 0 To UBound(StrArr)这一句的UBound(StrArr)值为1,我的txt文件大概有5万行左右,请问这是怎么回事?另外,请帮看看还有什么地方有问题?
Private Sub Command1_Click()
Dim FileName As String
Dim StrArr() As String
Dim TmpStr() As String
Dim WritStr As String
Dim I As Long
Dim B As Long
B = 1000
FileName = "c:\N1.txt"
'将文件读到一个字符串数组.
StrArr = RedTextFile(FileName)
For I = 0 To UBound(StrArr)
B = B + 1
TmpStr = Split(StrArr(I), " ")
'查找符合条件的项
If UCase$(TmpStr(0)) = "Site" And UCase$(TmpStr(1)) = "1:" Then
'修改该项
TmpStr(2) = "P" & B
StrArr(I) = TmpStr(0) & " " & TmpStr(1) & " " & TmpStr(2)
End If
WritStr = WritStr & StrArr(I) & Chr(13)
Next
'回写文件
WritTextFile FileName, WritStr
End Sub
'读TEXT文件
'函数:RedTextFile
'参数:FileName 打开的TXT文件名.
Public Function RedTextFile(FileName As String) As String()
Dim FileID As Long
Dim InputStr As String
Dim LineStr As String
Dim RevStr() As String
Dim ID As Long
On Error Resume Next
InputStr = "": LineStr = ""
FileID = FreeFile()
Open FileName For Input As #FileID
Do While Not EOF(FileID) ' 循环至文件尾。
LineStr = ""
ID = ID + 1
ReDim Preserve RevStr(ID)
Line Input #FileID, LineStr
RevStr(ID - 1) = LineStr
Loop
Close #FileID
RedTextFile = RevStr
Err.Clear
End Function
'写TEXT文件
'函数:WritTextFile
'参数:FileName 目标文件名.WritStr 写到目标的字符串.
'返回值:成功 返回文件内容.失败 返回""
'注:如果同名,目标字符串将覆盖原文件内容.
Public Function WritTextFile(FileName As String, WritStr As String) As Boolean
'/保存文件
Dim FileID As Long, ConTents As String
Dim A As Long, B As Long
On Error Resume Next
FileID = FreeFile
Open FileName For Output As #FileID
Print #FileID, WritStr
Close #FileID
WritTextFile = (Err.Number = 0)
Err.Clear
End Function