2

我正在循环输入文件并使用 readline 命令读取每一行,检查它的各种标准,然后我想根据结果进行更改。这是我正在尝试做的一个非常简单的版本:

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strFileLoc, 1)

Do While Not objFile.AtEndOfStream
     strLineRead = objFile.readline
     if strLineRead Like "*text to change*" Then
          'Some code to change the line
     end if
Loop

我一直在做的是将整个文件保存到一个名为 strFileText 的字符串中,然后使用 Replace 函数将该字符串中的 strLineRead 替换为更改后的版本。像这样的东西:

strFileText = Replace(strFileText, strLineRead, strNewLine)

然后将整个字符串写入一个新的文本文件。

问题是,有时我可能有一行的整个文本都是“NC”,然后在整个文件上查找/替换“NC”的变化不仅仅是一行。

那么 FileSystemObject 中是否有一个命令可以在某一行上直接更改文件?我在想类似“writeline”命令的东西。

4

1 回答 1

1

在您的文件和事件中的某个地方有这些私人潜艇,打电话给他们。首先调用 replace_text 并填写要求。请参阅我的示例代码。

    Private Sub Command3_Click()

    Dim sFileName As String
    Dim fileSys As Variant

    ' Edit as needed
    sFileName = Me.FileList.Value

    Set fileSys = CreateObject("Scripting.FileSystemObject")

    Replace_Text sFileName, "bad text", "good text", fileSys
    End Sub
    Private Sub Replace_Text(targetFile As String, targetText As String, replaceText As String, fileSys As Variant)
    If Right(targetFile, 3) = "filepath extension you want (example: xml or doc etc.)" Then
        Update_File targetFile, targetText, replaceText, fileSys
    Else
        MsgBox "You did not select the right file. Please try again."
    End If
    End Sub
    Private Sub Update_File(fileToUpdate As String, targetText As String, replaceText As String, fileSys As Variant)

    Dim tempName As String
    Dim tempFile As Variant
    Dim file As Variant
    Dim currentLine As String
    Dim newLine As String


        'creates a temp file and outputs the original files contents but with the replacements
        tempName = fileToUpdate & ".tmp"
        Set tempFile = fileSys.CreateTextFile(tempName, True)

        'open the original file and for each line replace any matching text
        Set file = fileSys.OpenTextFile(fileToUpdate)
        Do Until file.AtEndOfStream
            currentLine = file.ReadLine
            newLine = Replace(currentLine, targetText, replaceText)
            'write to the new line containing replacements to the temp file
            tempFile.WriteLine newLine
        Loop
        file.Close

        tempFile.Close

        'delete the original file and replace with the temporary file
        fileSys.DeleteFile fileToUpdate, True
        fileSys.MoveFile tempName, fileToUpdate
    End Sub
于 2013-08-14T13:19:54.267 回答