【问题标题】:reading and writing text file from VBA, the EOF() iteration only works 10% of the time从 VBA 读取和写入文本文件,EOF() 迭代只工作 10% 的时间
【发布时间】:2021-08-30 18:09:00
【问题描述】:

我试图编写一个 sub 来重写文本文件的第 27 行。但是EOF(1) 似乎只有 10% 的时间有效。其他时候它只是直接在第一个循环中运行,并且什么也不返回。有人知道原因吗?

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

我得到了运行时错误 9,下标超出范围。

【问题讨论】:

  • I got Run time error 9, subscript out of range - 显然是因为您的文件少于 26 行?

标签: vba text replace iteration file-writing


【解决方案1】:

试试这样的:

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

【讨论】:

    猜你喜欢
    • 2016-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-15
    • 2011-04-17
    • 1970-01-01
    • 1970-01-01
    • 2011-03-08
    相关资源
    最近更新 更多