+ Reply to Thread
Results 1 to 1 of 1

Giant merge macro with varying number of worksheets

Hybrid View

  1. #1
    Registered User
    Join Date
    10-13-2014
    Location
    Hong Kong
    MS-Off Ver
    MS Office 2007-2010
    Posts
    1

    Lightbulb Giant merge macro with varying number of worksheets

    I need a VBA code that copies everything in each sheet in hundreds of workbooks. Each workbook may contain multiple worksheets or just 1. In addition to this, I need a column at the end of it to tell me which data came from which file (so that I can locate the file for double checking).

    I have collected a code that does something similar and edited it to do the multiple sheets bit.
    My changes to the original code (found elsewhere on the net), are:
    - new variable NBS, used for counting number of worksheets in external workbook
    - relate a to NBS in subsequent lines when copying
    - added in the count function

    I'm not my edits are ok or not, for now I haven't ran into errors (yet).
    Could someone kindly give it a double check?

    Many thanks in advance!


    Option Explicit
    Const NUMBER_OF_SHEETS = 1 
    
    Public Sub GiantMerge()
        Dim externWorkbookFilepath As Variant
        Dim externWorkbook As Workbook
        Dim i As Long
        Dim a As Long
        Dim mainLastEnd(1 To NUMBER_OF_SHEETS) As Range
        Dim mainCurEnd As Range
        Dim NBS As Long
    
        Application.ScreenUpdating = False
    
        ' Initialise
    
        ' Correct number of sheets
        Application.DisplayAlerts = False
        If ThisWorkbook.Sheets.Count < NUMBER_OF_SHEETS Then
            ThisWorkbook.Sheets.Add Count:=NUMBER_OF_SHEETS - ThisWorkbook.Sheets.Count
        ElseIf ThisWorkbook.Sheets.Count > NUMBER_OF_SHEETS Then
            For i = ThisWorkbook.Sheets.Count To NUMBER_OF_SHEETS + 1 Step -1
                ThisWorkbook.Sheets(i).Delete
            Next i
        End If
        Application.DisplayAlerts = True
    
        For i = 1 To NUMBER_OF_SHEETS
            Set mainLastEnd(i) = GetTrueEnd(ThisWorkbook.Sheets(i))
        Next i
    
    
        ' Load the data
        For Each externWorkbookFilepath In GetWorkbooks()
            Set externWorkbook = Application.Workbooks.Open(externWorkbookFilepath, , True)
          NBS = externWorkbook.Worksheets.Count 'count number of sheets in the workbook with data to be copied
            For i = 1 To NUMBER_OF_SHEETS
            For a = 1 To NBS
                If mainLastEnd(i).Row > 1 Then
                    ' There is data in the sheet
    
                    ' Copy new data (skip headings)
                   externWorkbook.Sheets(a).Range("A2:" & GetTrueEnd(externWorkbook.Sheets(a)).Address).Copy ThisWorkbook.Sheets(i).Cells(mainLastEnd(i).Row + 1, 1)
                    ' Find the end column and row
                    Set mainCurEnd = GetTrueEnd(ThisWorkbook.Sheets(i))
                Else
                    ' No nata in sheet yet (prob very first run)
    
                    ' Get correct sheet name from first file we check
                    ThisWorkbook.Sheets(i).Name = externWorkbook.Sheets(i).Name
    
                    ' Copy new data (with headings)
                    externWorkbook.Sheets(a).Range("A1:" & GetTrueEnd(externWorkbook.Sheets(a)).Address).Copy ThisWorkbook.Sheets(i).Cells(mainLastEnd(i).Row, 1)
                    ' Find the end column and row
                    Set mainCurEnd = GetTrueEnd(ThisWorkbook.Sheets(i)).Offset(, 1)
    
                    ' Add file name heading
                    ThisWorkbook.Sheets(i).Cells(1, mainCurEnd.Column).Value = "File Name"
                End If
    
                ' Add file name into extra column
                ThisWorkbook.Sheets(i).Range(ThisWorkbook.Sheets(i).Cells(mainLastEnd(i).Row + 1, mainCurEnd.Column), mainCurEnd).Value = externWorkbook.Name
    
                Set mainLastEnd(i) = mainCurEnd
            Next a
            Next i
    
            externWorkbook.Close
        Next externWorkbookFilepath
    
        Application.ScreenUpdating = True
    End Sub
    
    ' Returns a collection of file paths, or an empty collection if the user selects cancel
    Private Function GetWorkbooks() As Collection
        Dim fileNames As Variant
        Dim xlFile As Variant
    
        Set GetWorkbooks = New Collection
    
        fileNames = Application.GetOpenFilename(Title:="Please choose the files to merge", _
                                                   FileFilter:="Excel Files, *.xls;*.xlsx", _
                                                   MultiSelect:=True)
        If TypeName(fileNames) = "Variant()" Then
            For Each xlFile In fileNames
                GetWorkbooks.Add xlFile
            Next xlFile
        End If
    End Function
    
    ' Finds the true end of the table (excluding unused columns/rows and rows filled with 0's)
    Private Function GetTrueEnd(ws As Worksheet) As Range
        Dim lastRow As Long
        Dim lastCol As Long
        Dim r As Long
        Dim c As Long
    
        On Error Resume Next
        lastCol = ws.UsedRange.Find("*", , , xlPart, xlByColumns, xlPrevious).Column
        lastRow = ws.UsedRange.Find("*", , , xlPart, xlByRows, xlPrevious).Row
        On Error GoTo 0
    
        If lastCol <> 0 And lastRow <> 0 Then
    
            ' look back through the last rows of the table, looking for a non-zero value
            For r = lastRow To 1 Step -1
                For c = 1 To lastCol
                    If ws.Cells(r, c).Text <> "" Then
                        If ws.Cells(r, c).Text <> 0 Then
                            Set GetTrueEnd = ws.Cells(r, lastCol)
                            Exit Function
                        End If
                    End If
                Next c
            Next r
        End If
    
        Set GetTrueEnd = ws.Cells(1, 1)
    End Function
    Last edited by Knighterist; 11-06-2014 at 11:36 AM.

+ Reply to Thread

Thread Information

Users Browsing this Thread

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

Similar Threads

  1. Help needed
    By LiewDickson in forum Excel Formulas & Functions
    Replies: 2
    Last Post: 11-14-2013, 10:10 AM
  2. Complex Filter/Sorting Help Needed (VBA knowledge needed)
    By dfxryanjr in forum Excel Programming / VBA / Macros
    Replies: 7
    Last Post: 07-03-2013, 01:39 PM
  3. Help needed
    By javed65 in forum Excel General
    Replies: 1
    Last Post: 03-03-2013, 11:16 PM
  4. Conditional formatting needed for shape colour - is programming needed?
    By Farmboyuk in forum Excel Programming / VBA / Macros
    Replies: 1
    Last Post: 08-14-2012, 07:27 AM
  5. search engine tool problem with ending find, please help.
    By golden444 in forum Excel Programming / VBA / Macros
    Replies: 1
    Last Post: 05-20-2012, 11:36 AM

Tags for this Thread

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