Results 1 to 28 of 28

Thread: [RESOLVED] Editing one line of a txt file?

Hybrid View

  1. #1
    Hyperactive Member BrendanDavis's Avatar
    Join Date
    Oct 2006
    Location
    Florida
    Posts
    492

    Re: Editing one line of a txt file?

    VB Code:
    1. Dim file As String
    2.  
    3. Open "C:\Test.txt" For Input As #1: file = Input(LOF(1), #1): Close #1
    4.     file = Replace(file, "Selected car xxx", "Selected car " & Label1.Caption, 1, 1)
    5. Open "C:\Test.txt" For Output As #1: Print #1, file: Close #1

    That'll replace the first instance of "Selected car xxx" and no other, with "Selected car " & the label's caption.

    If your string or file contains several instances of "Selected car xxx" before the one you wish to replace, you can simply do something like:

    VB Code:
    1. Dim file() As String, i As Integer, count As Integer: count = 0
    2.  
    3. Open "C:\Test.txt" For Input As #1: file = Split(Input(LOF(1), #1), vbCrLf): Close #1
    4.  
    5. For i = 0 To UBound(file)
    6.     If InStr(file(i), "Selected car xxx") > 0 Then count = count + 1
    7.     If count = 4 Then 'Find the fourth instance of the phrase
    8.         newfile = newfile & Replace(file(i), "Selected car xxx", "Selected car " & _
    9.         Label1.Caption) & vbNewLine
    10.     Else
    11.         newfile = newfile & file(i) & vbNewLine
    12.     End If
    13. Next
    14.  
    15. Open "C:\Test.txt" For Output As #1: Print #1, Mid(newfile, 1, Len(newfile) - 2): Close #1

    In that example, it will find the 4th instance of "Selected car xxx" and replace only it with "Selected car " & Label1.Caption, and leave the other instances alone. Change the "4" in:

    VB Code:
    1. If count = 4 Then

    ...to whatever number instance you wish to find(26th, 62nd, whatever).

    If all you need to do is replace something that will ALWAYS be on a certain line, then you could use one of the examples already provided by the other users here ;D
    Last edited by BrendanDavis; Feb 4th, 2007 at 01:17 AM.
    God put me on this earth to do many great things, and I'm so far behind that I'm going to live forever.

    I'm programming for Windows using a Apple Mac Mini, 1.5Ghz with 512MB DDR RAM. I feel like I'm committing a crime :P

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width