将光标移动到用VBA写入文本文件的特定行中

我想知道如何使用VBA将文本文件的特定行replace为另一个文本,并通过移动光标来写入文本文件的特定区域。

您需要自己跟踪职位,并相应地应用逻辑。

像这样的东西:

Dim text As String, allText As String Dim lineNumber As Integer ' Open read handle. Open "C:\sometext.txt" For Input As #1 allText = "" lineNumber = 0 Do Until EOF(1) lineNumber = lineNumber + 1 Line Input #1, text ' Assume you want to replace line 5. If lineNumber = 5 Then text = "My new value" End if allText = allText & vbCrLf & text Loop ' Close read handle. Close #1 ' Output the new text to a separate file. Open "C:\updatedtext.txt" For Append As #1 Write #1, allText Close #1 

这个怎么样:

 Dim TextString As Variant 'read text from file TextString = Split(CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\sometext.txt").ReadAll, Chr(13) & Chr(10)) 'change your text here as TextString(#Line - 1) = "Text" 'still assume you want to replace line 5 TextString(4) = "New Text" 'write back in file CreateObject("Scripting.FileSystemObject").CreateTextFile("C:\sometext.txt").Write (Join(TextString, Chr(13) & Chr(10))) 

我觉得这很简单,因为只有一行可以阅读,另外一个可以写。 没有循环或closures文件或类似的东西。