简体   繁体   中英

Move cursor to write in specific line of a text file with VBA

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

How about this:

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)))

I think it's pretty simple cuz there is only one line to read and another one to write. No loops or closing files or anything like that.

You would need to keep track of the positions yourself and apply the logic accordingly.

Something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM