otus
otus

Reputation: 385

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

I would like to know how I can use VBA to replace a specific line of a text file by another text, and to write in specific zone of the text file by moving the cursor.

Upvotes: 1

Views: 4868

Answers (2)

Dirk Reichel
Dirk Reichel

Reputation: 7979

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.

Upvotes: 2

Jason Faulkner
Jason Faulkner

Reputation: 6568

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

Upvotes: 0

Related Questions