如何在VBA中使用FileSystemObjectreplace一行文本文件中的string?

我正在尝试使用FileSystemObject方法在文本文件中查找特定的行,并在该行内replace特定的string。 我相对比较新,因为我目前的代码有excel打开文本文件,并取代我需要它replace然后保存并closures它。 这种方式不再是一个选项,因为有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 

我能做的最好的是打开文件写入,但我不知道如何find该行,并将其replace为我需要replace的行。

请让我知道,如果你愿意帮助/引导我在正确的方向,你需要更多的信息。 我搜查了很多,看到有人提出了其他的方法。 我需要学习如何以这种方式编辑线条。 有人可以帮帮我吗?

提前致谢!

– 安东尼

不知道这是否是最有效的方法,但有一个想法是使用FileSystemObject的CreateTextFile方法创build另一个可以写入的文件。

我已经在一个小文件上testing了这个,看起来像预期的那样工作。

接受答案后修改,以避免.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 

然后,根据您是否想要摆脱“原始”文件,您可以执行如下操作:

 '# 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 

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 

你所有的文本文件数据现在在数组strData只是循环数组,并find你想要replace的文本,并将其写回到SAME文件。