如何逐行修改文件

时间:2019-07-09 08:08:41

标签: vba access-vba

我有一个使用以下语法的txt文件:

'foo','bar'
'foo','foo bar'
'foo','foo
bar bar'
'bar', 'foo'

我想找到每条不以'开头的行并进行更正。我想结束:

'foo','bar'
'foo','foo bar'
'foo','foo bar bar'
'bar', 'foo'

必须删除新行,并将其添加到前一行的末尾,并带有前导空格。 我的代码逐行遍历文件,并检查第一个字符是否已经不等于'

我考虑过将每一行添加到数组中并在该数组中进行校正。 我会用

Open myFile For Output As #1
Write #1, lineOfArray
Close #1

更新文件。

我当前的代码:

Sub Update_File(fileToUpdate As String, fileSys As Variant)

    Set File = fileSys.OpenTextFile(fileToUpdate)
    Do Until File.AtEndOfStream
        currentLine = File.ReadLine

        If Left(currentFile, 1) <> "'" Then
            'Magic here
        End If
    Loop
    File.Close

End Sub

我正在努力寻找最佳实践以及精简和快速的代码,因为该脚本最后应运行超过1000个文件。 我不知道是否可以存储当前行和下一行,并且如果下一行不是以'开头,然后以currentLine = currentLine & " " & nextLine开头并以某种方式更新文件,则将循环值减小一个继续吧。

3 个答案:

答案 0 :(得分:1)

这就是我要怎么做。

Sub Update_File(ByVal FilePath As String, ByRef fso As Object)
    Const ForReading = 1

    Dim lines() As String
    Dim r As Long
    Dim Dirty As Boolean

    With fso.OpenTextFile(FilePath, ForReading)
        lines = Split(.ReadAll, vbNewLine)
        .Close
    End With

    For r = 0 To UBound(lines)
        If Left(lines(r), 1) <> "'" Then
            lines(r) = "'" & lines(r)
            Dirty = True
        End If
    Next

    If Dirty Then
        With fso.CreateTextFile(FilePath, True)
            .Write Join(lines, vbNewLine)
            .Close
        End With
    End If

End Sub

答案 1 :(得分:1)

基于TinMan的出色代码,请尝试以下vserion

Sub Test_UpdateFile()
UpdateFile ThisWorkbook.Path & "\Sample.txt", CreateObject("Scripting.FileSystemObject")
End Sub

Sub UpdateFile(ByVal filePath As String, ByRef fso As Object)
Const forReading = 1

Dim lines()     As String
Dim dirty       As Boolean
Dim r           As Long
Dim x           As Long
Dim k           As Long

With fso.OpenTextFile(filePath, forReading)
    lines = Split(.ReadAll, vbNewLine)
    .Close
End With

For r = 1 To UBound(lines)
    If Left(lines(r), 1) <> "'" Then
        lines(r - 1) = lines(r - 1) & " " & lines(r)
        lines(r) = Empty
        dirty = True
        x = x + 1
    End If
Next r

If dirty Then
    ReDim nLines(0 To UBound(lines) - x + 1)

    For r = 0 To UBound(lines)
        If lines(r) <> Empty Then
            nLines(k) = lines(r)
            k = k + 1
        End If
    Next r


    With fso.CreateTextFile(filePath, True)
        .Write Join(nLines, vbNewLine)
        .Close
    End With
End If
End Sub

答案 2 :(得分:0)

那呢:

currentline = File.ReadLine
NextLine = vbNullString
Do 
    If Not File.AtEndOfStream Then
        NextLine = File.ReadLine

        Do While Left$(NextLine, 1) <> "'"
            If Len(currentline) > 0 Then currentline = Trim(currentline) & " "
            currentline = currentline & Trim(NextLine)
            NextLine = File.ReadLine
        Loop
    End If

    Write #1, currentline
    currentline = NextLine

Loop Until File.AtEndOfStream