如何在VBA中使用FileSystemObject替换文本文件行中的字符串?

aCa*_*lla 6 excel vba text file filesystemobject

我正在尝试使用FileSystemObject方法在文本文件中查找特定行,并在该行内替换特定字符串.我对此比较陌生,因为我当前的代码已经excel打开文本文件并替换我需要它替换然后保存并关闭它.这种方式不再是一种选择,因为excel打开文本文件需要太长时间并保留文件.

到目前为止,我已经走了多远.

-

Sub FindLines()

Const ForReading = 1

Set FSO = CreateObject("Scripting.FileSystemObject")

Set objFSO = FSO.OpenTextFile("C:\Users\Carella Home\Desktop\boomboom.txt", ForReading,     False)

Do Until objFSO.AtEndOfStream = True

    go = objFSO.ReadLine

    If InStr(1, go, "ant", vbTextCompare) > 0 Then

        bo = Replace(go, "t", "wow")

    End If

Loop

objFSO.Close

Set objFSO = FSO.OpenTextFile("C:\Users\Carella Home\Desktop\boomboom.txt", 2)

End Sub
Run Code Online (Sandbox Code Playgroud)

-

我能做的最好是打开文件写入,但我不知道如何找到该行并将其替换为我需要替换它的行.

如果您愿意帮助/指导我正确的方向,请告知我们您需要更多信息.我经常搜索并看到人们建议其他方法.我需要学习如何以这种方式编辑线条.有人可以帮帮我吗?

提前致谢!

-Anthony C.

Dav*_*ens 9

不确定这是否是最有效的方法,但有一个想法是使用的CreateTextFile方法FileSystemObject创建另一个可以写入的文件.

我在一个小文件上测试了这个,看起来像预期的那样工作.

在接受回答后修改以避免.ReadLine.WriteLine循环

Sub FindLines()
'Declare ALL of your variables :)
Const ForReading = 1    '
Const fileToRead As String = "C:\Users\david_zemens\Desktop\test.txt"  ' the path of the file to read
Const fileToWrite As String = "C:\Users\david_zemens\Desktop\test_NEW.txt"  ' the path of a new file
Dim FSO As Object
Dim readFile As Object  'the file you will READ
Dim writeFile As Object 'the file you will CREATE
Dim repLine As Variant   'the array of lines you will WRITE
Dim ln As Variant
Dim l As Long

Set FSO = CreateObject("Scripting.FileSystemObject")
Set readFile = FSO.OpenTextFile(fileToRead, ForReading, False)
Set writeFile = FSO.CreateTextFile(fileToWrite, True, False)

'# Read entire file into an array & close it
repLine = Split(readFile.ReadAll, vbNewLine)
readFile.Close

'# iterate the array and do the replacement line by line
For Each ln In repLine
    ln = IIf(InStr(1, ln, "ant", vbTextCompare) > 0, Replace(ln, "t", "wow"), ln)
    repLine(l) = ln
    l = l + 1
Next

'# Write to the array items to the file
writeFile.Write Join(repLine, vbNewLine)
writeFile.Close

'# clean up
Set readFile = Nothing
Set writeFile = Nothing
Set FSO = Nothing

End Sub
Run Code Online (Sandbox Code Playgroud)

然后,根据您是否要删除"原始"文件,您可以执行以下操作:

'# clean up
Set readFile = Nothing
Set writeFile = Nothing
'# Get rid of the "old" file and replace/rename it with only the new one
Kill fileToRead
Name fileToWrite As fileToRead
End Sub
Run Code Online (Sandbox Code Playgroud)


Sid*_*out 5

与此相比,这是一种更快,更短的方法 FileSystemObject

Sub Sample()
    Dim MyData As String, strData() As String

    '~~> Read the file in one go!
    Open "C:\Users\Carella Home\Desktop\boomboom.txt" For Binary As #1
    MyData = Space$(LOF(1))
    Get #1, , MyData
    Close #1
    strData() = Split(MyData, vbCrLf)
End Sub
Run Code Online (Sandbox Code Playgroud)

您的所有文本文件数据现在都在数组中通过数组strData循环,找到要替换的文本并将其写回SAME文件.

  • 原因很简单.此方法更快,因为您不循环文本文件的每一行.你正在做的是一次性将完整的文本文件加载到数组中(到内存中),然后在该数组上执行操作. (2认同)