简体   繁体   中英

Exporting text from from multiple Excel files to a single comma delimited file

I need to export data from Excel to a comma delimited file. I am using a button that runs a macro that creates the text file in a location I specify and exports values.

But, I want to copy this Excel with the same macro, and add different values. When I run the macro in the copied Excel file I want the same text delimited file to add these values under the previous set of values, not overwrite the values from the first Excel file.

How is this possible? I want to use the same text file each time.

Append using following routine:

Sub writeCSV(ByVal thisRange As Range, ByVal filePath As String, _
             Optional ByVal fileAppend As Boolean = False)
    Dim cLoop As Long, rLoop As Long
    Dim ff As Long, strRow As String

    ff = FreeFile
    If fileAppend Then
        Open filePath For Append As #ff
    Else
        Open filePath For Output As #ff
    End If

    For rLoop = 1 To thisRange.Rows.Count
        strRow = ""
        For cLoop = 1 To thisRange.Columns.Count
            If cLoop > 1 Then strRow = strRow & ","
            strRow = strRow & thisRange.Cells(rLoop, cLoop).Value
        Next 'cLoop
        Print #ff, strRow
    Next 'rLoop

    Close #ff
End Sub

Example usage

writeCSV sheet1, "c:\test.txt", true

It is easy to do it by using a StreamWriter . The AppendText function of the FileInfo class returns one that is configured for appending text to an existing file.

I write my example as pseudo code, as I don't know how you are retrieving the information from Excel. The File handling part, however, is complete:

Dim file As New FileInfo("C:\myOuputFile.csv")
Using writer = file.AppendText()
    While isRowAvailable
        writer.WriteLine("Write next row")
    End While
End Using

The Using statement automatically closes the file at the end.

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