[英]reading and writing text file from VBA, the EOF() iteration only works 10% of the time
I was trying to write a sub to rewrite line 27 of a text file.我试图编写一个 sub 来重写文本文件的第 27 行。 But the EOF(1)
seems only work 10% of the time.但是EOF(1)
似乎只有 10% 的时间有效。 Other times it just directly run down with the 1st loop, and returns nothing.其他时候它只是直接在第一个循环中运行,并且什么也不返回。 Anyone know the reason?有人知道原因吗?
Dim File As String
Dim VecFile() As String, Aux As String
Dim i As Long, j As Long
Dim SizeNewFile As Long
Open (filepath) For Input As 1
i = 0
j = 0
Do Until EOF(1)
j = j + 1
Line Input #1, Aux
If j <> 27 Then
i = i + 1
ReDim Preserve VecFile(1 To i)
VecFile(i) = Aux
End If
Loop
Close #1
SizeNewFile = i
'Write array to file
Open ("filepath") For Output As 1
For i = 1 To 26
Print #1, VecFile(i)
Next i
Print #1, "\newcommand\casenumber{" & Sheets("Database").Range("$B$1").Value & "}" & Chr(13) & Chr(10)
For i = 28 To SizeNewFile
Print #1, VecFile(i)
Next i
Close #1
I got Run time error 9, subscript out of range.我得到了运行时错误 9,下标超出范围。
Try something like this instead:尝试这样的事情:
Sub Tester()
Const FILE_PATH As String = "C:\Tester\Modify Me.txt"
Dim arr, txt
With CreateObject("scripting.filesystemobject")
txt = .opentextfile(FILE_PATH, 1).readall() 'read all content
arr = Split(txt, vbCrLf) 'zero-based array from file content
'modify content if reached required # of lines
If UBound(arr) >= 26 Then arr(26) = "---New line goes here---"
txt = Join(arr, vbCrLf)
.opentextfile(FILE_PATH, 2, True).write txt 'write back modified text
End With
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.