TheSwamp

Code Red => VB(A) => Topic started by: iliekater on April 05, 2008, 07:08:38 PM

Title: Reading and writting data in a file
Post by: iliekater on April 05, 2008, 07:08:38 PM
I know one can use the Open for Input and the Open for Output statements , but is there a way to write in a file on specific line ?
For example , in a file of mine I have stored some variables :

.....
"air" , "3" , "bla bla bla"
......

I want to go and write directly on the line above , not to write the whole file again . Is it possible ? Let me specify here that I know the exact line (number or row) at which I want to write my new variables . The problem is how do I write at exactly at that line ? ...
Title: Re: Reading and writting data in a file
Post by: Fatty on April 06, 2008, 03:03:41 AM
Yes, you can
Change file names to suit:


Code: [Select]
Option Explicit

Sub EditTextFile()

Dim newline As String
Dim strline As String, strarr As Variant, i As Long, pos As Long
newline = "String to be added"
pos = 3 '<--position to insert the new line, zero based, change to suit
    Open "C:\MyFolder\fatty.txt" For Input As #1: strline = Input(LOF(1), 1): Close #1
    strarr = Split(strline, vbCrLf)
    Open "C:\MyFolder\fatty1.txt" For Output As #1 '<--temporary file name
 For i = 0 To UBound(strarr) - 1
    If pos <> i Then
    strline = strarr(i)
Else
    strline = newline & vbCrLf & strarr(i)
    End If
    Print #1, strline
    strline = ""
 Next
Close #1: Kill "C:\MyFolder\fatty.txt"
      Name "C:\MyFolder\fatty1.txt" _
      As "C:\MyFolder\fatty.txt"

End Sub

~'J'~
Title: Re: Reading and writting data in a file
Post by: iliekater on April 06, 2008, 11:57:22 AM
Thanks Fatty . I owe you a beer . Well , many more beers !  :-)
Title: Re: Reading and writting data in a file
Post by: Fatty on April 06, 2008, 03:47:25 PM
Always glad to help
Happy computing :)

~'J'~
Title: Re: Reading and writting data in a file
Post by: ML on April 15, 2008, 03:45:51 PM

IL

There sure is:

Have you ever tried  textstream method?

It is commonly used in VB Scripting; I use it all of the time in VBA...

I would be glad to post an example or send you something if you'd like...

Mark