ExcelBanter

ExcelBanter (https://www.excelbanter.com/)
-   Excel Discussion (Misc queries) (https://www.excelbanter.com/excel-discussion-misc-queries/)
-   -   Append text (https://www.excelbanter.com/excel-discussion-misc-queries/131106-append-text.html)

Jeff

Append text
 
Hi,

I am writing a string to an existing csv file.
I have the csv file opened and I want to append text to the csv file. How
is this done

For i = 1 to 100
Write #1, Array(i) 'Write this to the end of the csv file
next i

The csv file is very large - around 100mb

Thanks for your help on this

JLatham

Append text
 
Have you already written the section of code to open the .csv to be written
to? I'm thinking not?

Make a copy of the .csv file to test this with so that your original doesn't
get messed up if I steer you wrong. If I'm wrong, no harm done, if I'm
right, then you have copy with the data appended.

Sub AddToCSVFile()
Dim myFileNum As Integer
Dim LC As Integer ' same as your 'i'
Dim myArray(1 to 100) as Integer ' same as your Array() - alter as needed

'....your code to create and fill Array() here

myFileNum = Freefile()
'change the path and name below as required
Open "C:\My Documents\myCSVFile.csv" For Append As #myFileNum
For LC = LBound(myArray) to UBound(myArray)
Print #myFileNum, myArray(LC)
Next
Close #myFileNum
'... more code here perhaps
End Sub

That is going to simply append the contents of myArray() as added 'rows' to
the .csv file. If each element of myArray() holds multiple entries that need
to be written as column information then we have to know a little more about
the array and what's in it.

But assume it is a 2 dimensional array as
Dim myArray(1 to 100,1 to 5) As String
then you could write the loop this way
Dim RC as Integer ' row counter for loop
Dim CC as Integer ' column counter for loop

For RC=1 to 100
For CC = 1 to 4 ' yes, 4 not 5 - you'll see
Print #myFileNum myArray(RC,CC) & ","; ' note the semi-colon use
Next ' ends CC loop
Print #myFileNum myArray(RC,5) ' write last element and terminate 'row'
Next ' ends RC loop

Finally, if the data in the array contains text and that text may contain
the separator character (comma) then it needs to be written this way:

For RC=1 to 100
For CC = 1 to 4 ' yes, 4 not 5 - you'll see
Print #myFileNum Chr(34) & myArray(RC,CC) & Chr(34) & ","; ' note the
semi-colon use
Next ' ends CC loop
Print #myFileNum Chr(34) & myArray(RC,5) & Chr(34) ' write last element and
terminate 'row'
Next ' ends RC loop




"Jeff" wrote:

Hi,

I am writing a string to an existing csv file.
I have the csv file opened and I want to append text to the csv file. How
is this done

For i = 1 to 100
Write #1, Array(i) 'Write this to the end of the csv file
next i

The csv file is very large - around 100mb

Thanks for your help on this



All times are GMT +1. The time now is 11:15 PM.

Powered by vBulletin® Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
ExcelBanter.com