+ Reply to Thread
Results 1 to 6 of 6

Merge several worksheets into the same .csv file

Hybrid View

  1. #1
    Registered User
    Join Date
    09-10-2010
    Location
    France
    MS-Off Ver
    Excel 2007
    Posts
    17

    Merge several worksheets into the same .csv file

    Hello,

    I have the code which allows me to save a worksheet as a .csv file.

    However, the reason I am converting to .cvs is that each worksheet has about 50,000 rows

    How can I parse through all the worskheets and save them, one after the other, in the same .csv file?

    Here comes the code so far. This subroutine, as far as I understand it (even though I am the author :-) ) will only keep the last worksheet in the .csv file

    Public Sub ConvertDataToCSV()
    
    Dim PathToFiles As String
    PathToFiles = ThisWorkbook.path & "\" 
    Dim DataFile As String
    Dim i As Integer, Row As Long, Col As Integer
    DataFile = PathToFiles & ThisFileName 'Filename defined as a global variable
    
    If FileFolderExists(DataFile) Then 'subroutine to check whether a file exists
        Dim wb As Workbook
        Application.ScreenUpdating = False ' turn off the screen updating
        'open the source workbook, read only
        Set wb = Workbooks.Open(DataFile, True, False)
        i = 0
        Dim First_Col As Integer, First_Row As Long
        Dim Last_Col As Integer, Last_Row As Long
        Dim sht As Worksheets
        Dim FileName As String
        Dim NumberOfWorksheets As Integer
        NumberOfWorksheets = wb.Worksheets.count
        Dim TemporaryTable() As Variant
        For i = 1 To NumberOfWorksheets
            First_Row = wb.Worksheets(i).Cells.Find(What:="*", SearchDirection:=xlNext, SearchOrder:=xlByRows).Row
            First_Col = wb.Worksheets(i).Cells.Find(What:="*", SearchDirection:=xlNext, SearchOrder:=xlByColumns).Column
            Last_Row = wb.Worksheets(i).Cells.Find(What:="*", SearchDirection:=xlPrevious, SearchOrder:=xlByRows).Row
            Last_Col = wb.Worksheets(i).Cells.Find(What:="*", SearchDirection:=xlPrevious, SearchOrder:=xlByColumns).Column
            If First_Col > 1 Then
                For Col = 1 To First_Col - 1
                    Application.DisplayAlerts = False
                    wb.Worksheets(i).Columns(Col).EntireColumn.Delete
                Next Col
                First_Col = 1
            End If
            FileName = "SavedFile.csv"
            FileName = PathToFiles & FileName
            Application.DisplayAlerts = False
            'Forcing US parameters with Local:=False => comma. Do not know how to force semi-colon
            wb.Worksheets(i).SaveAs FileName:=FileName, FileFormat:=xlCSVWindows, CreateBackup:=False, Local:=False
        Next i
        With wb
            Application.DisplayAlerts = False
            .SaveAs FileName:=DataFile, FileFormat:=56
            .Close SaveChanges:=False
        End With
    
        Set wb = Nothing ' free memory
    Else
        MsgBox "No new references available"
    End If
    
    Application.ScreenUpdating = True ' turn on the screen updating
    
    End Sub
    And by the way, if anyone knows how to save a .csv with semi-colon separator I will be infinitely grateful, too

    Thank you in advance
    Last edited by NiceLittleRabbit; 01-13-2011 at 06:39 AM.

  2. #2
    Registered User
    Join Date
    09-10-2010
    Location
    France
    MS-Off Ver
    Excel 2007
    Posts
    17

    Re: Merge several worksheets into the same .csv file

    Hello,

    Is it impossible? No one to help?

  3. #3
    Forum Expert pike's Avatar
    Join Date
    12-11-2005
    Location
    Alstonville, Australia
    MS-Off Ver
    2016
    Posts
    5,330

    Re: Merge several worksheets into the same .csv file

    Hi NiceLittleRabbit

    you could adapt this
    ConvertDataToCSV
        Dim ExpRng As Range
         Dim ws As Worksheet
        Open ThisWorkbook.Path & "\csvfileone.csv" For Output As #1
             For Each ws In Worksheets
        Set ExpRng = ws.Range("A1").CurrentRegion
        FirstCol = ExpRng.Columns(1).Column
        LastCol = FirstCol + ExpRng.Columns.Count - 1
        FirstRow = ExpRng.Rows(1).Row
        LastRow = FirstRow + ExpRng.Rows.Count - 1
            For r = FirstRow To LastRow
                For c = FirstCol To LastCol
                    data = ExpRng.Cells(r, c).Value
                    If data = "" Then data = ""
                    If IsNumeric(data) Then data = Val(data)
                    If c <> LastCol Then
                        Write #1, data;
                    Else
                        Write #1, data
                    End If
                Next c
            Next r
       
       Set ExpRng = Nothing
        Next ws
    Close #1
    End Sub
    If the solution helped please donate to RSPCA

    Site worth visiting: Rabbitohs

  4. #4
    Registered User
    Join Date
    09-10-2010
    Location
    France
    MS-Off Ver
    Excel 2007
    Posts
    17

    Re: Merge several worksheets into the same .csv file

    Hello Pike,

    Thank you for your answer. I actually had a code where I copied the data in the .csv file myself, as I think you are proposing to do here.

    The issue I had was that .csv has a lot of different rules and by simply copying the data I always missed one rule or the other (for instance the number of quotes before and after a cell which already has a weird number of quotes itself), so that the .csv reader (which is a specific program, not Excel and which is purely based on the .csv rules) always complained and could not read the full file. So this is why I would like to use the Excel built-in saveas .csv

    The code I am talking about (which may actually have been adapted from yours ) is:
    Public Sub SaveAsCSV(MyArray() As Variant, sFileName As String, AppendOrNew As Boolean, Optional SepChar As String = ";")
    
    'AppendOrNew = True => Append
    Dim n As Long 'counter
    Dim M As Long 'counter
    Dim sCSV As String 'csv string to print
    Dim fn As Integer
    Dim Dimensions As Integer
    Dim LastRow As Long, LastCol As Long, FirstRow As Long, FirstCol As Long
        
    If UCase(SepChar) = "TAB" Or UCase(SepChar) = "T" Then
        SC = Chr(9)
    Else
        SC = Left(SepChar, 1)
    End If
    
    fn = FreeFile
    
    'check extension and correct if needed
    If InStr(sFileName, ".csv") = 0 Then
      sFileName = sFileName & ".csv"
    Else
      Do While (Len(sFileName) - InStr(sFileName, ".csv")) > 3
        sFileName = Left(sFileName, Len(sFileName) - 1)
      Loop
    End If
    
    Dimensions = cArrayDimensions(MyArray)
    
    If Dimensions = 1 Then '1 dimension
    
        LastRow = UBound(MyArray)
        FirstRow = LBound(MyArray)
    
      'save the file
      If AppendOrNew Then
        Open sFileName For Append As #fn
      Else
        Open sFileName For Output As #fn
      End If
      For n = FirstRow To LastRow
        Print #fn, MyArray(n, 0)
      Next n
      Close #fn
      
    Else 'more dimensional
    
        LastRow = UBound(MyArray, 1)
        LastCol = UBound(MyArray, 2)
        FirstRow = LBound(MyArray, 1)
        FirstCol = LBound(MyArray, 2)
    
      'save the file
      If AppendOrNew Then
        Open sFileName For Append As #fn
      Else
        Open sFileName For Output As #fn
      End If
      For n = FirstRow To LastRow
        sCSV = ""
        For M = FirstCol To LastCol
          sCSV = sCSV & MyArray(n, M) & SC
        Next M
        sCSV = Left(sCSV, Len(sCSV) - 1) 'remove last Delimiter
    '    sCSV = sCSV & vbCr ' Add a carriage return
        Print #fn, sCSV
      Next n
      Close #fn
      
    End If
    
    End Sub
    Any idea?

  5. #5
    Forum Expert pike's Avatar
    Join Date
    12-11-2005
    Location
    Alstonville, Australia
    MS-Off Ver
    2016
    Posts
    5,330

    Re: Merge several worksheets into the same .csv file

    hi NiceLittleRabbit,
    if you place all the data in one worksheet you could then save that one sheet as a csv file
    you cant save more that one sheet as one csv file by saveas

  6. #6
    Registered User
    Join Date
    09-10-2010
    Location
    France
    MS-Off Ver
    Excel 2007
    Posts
    17

    Re: Merge several worksheets into the same .csv file

    Thank you Pike

    Given that each sheet has over 50,000 rows, I then conclude that it is not possible to save several large worksheets into one CSV file using the saveas function in Excel.

    I will thus certainly have to create several .csv files, use either shell + Dos command or come back to Excel's VBA to merge them into one and delete the additional .csv files. Complicating simple things ... :-(

    Thank you Pike for your help

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

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

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1