Combine worksheets

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sandy armstrong
    New Member
    • Oct 2011
    • 88

    Combine worksheets

    Good Morning Everyone.
    i would like to merge 6 workbook together they are all the same format all with the same headers and are all in the same folder called merged. I have this code ( below) but i keep getting User defined error on line 3and i dont understand why... Some please help me merge these files together i would appreciate it sooo much

    Thanks




    Code:
    Sub MergeAllSheets()
      Dim rs As Recordset
      Dim mergedRS As Recordset
      Dim sh As Worksheet
      Dim wb As Workbook
     
      Dim fieldList As New Collection
      Dim rsetList As New Collection
     
      Dim f As Variant
      Dim cols As Long
      Dim rows As Long
      Dim c As Long
      Dim r As Long
     
      Dim ref As String
      Dim fldName As String
      Dim sourceColumn As String
     
     
     
      Set wb = ActiveWorkbook
      For Each sh In wb.Worksheets
        Set rs = New Recordset
        ref = FindEndCell(sh)
        cols = sh.Range(ref).Column
        rows = sh.Range(ref).Row
     
        If ref <> "$A$1" Or sh.Range(ref).Value <> "" Then '' This is to catch empty sheet
          c = 1
          r = 1
          Do While c <= cols
            fldName = sh.Cells(r, c).Value
            rs.Fields.Append fldName, adVarChar, MAX_CHARS
            If Not InCollection(fieldList, fldName) Then
              fieldList.Add fldName, fldName
            End If
            c = c + 1
          Loop
          rs.Open
     
     
          r = 2
          Do While r <= rows
            rs.AddNew
            c = 1
            Do While c <= cols
              rs.Fields(c - 1) = CStr(sh.Cells(r, c).Value)
              c = c + 1
            Loop
            r = r + 1
            Debug.Print sh.Name & ": " & r & " of " & rows & ", " & c & " of " & cols
          Loop
          rsetList.Add rs, sh.Name
        End If
      Next
     
     
      Set mergedRS = New Recordset
      c = 1
      sourceColumn = "SourceSheet"
      Do While InCollection(fieldList, sourceColumn) '' Just in case you merge a merged sheet
        sourceColumn = "SourceSheet" & c
        c = c + 1
      Loop
      mergedRS.Fields.Append sourceColumn, adVarChar, MAX_CHARS
      For Each f In fieldList
        mergedRS.Fields.Append CStr(f), adVarChar, MAX_CHARS
      Next
      mergedRS.Open
     
      c = 1
      For Each rs In rsetList
        If rs.RecordCount >= 1 Then
          rs.MoveFirst
          Do Until rs.EOF
            mergedRS.AddNew
            mergedRS.Fields(sourceColumn) = "Sheet No. " & c
            For Each f In rs.Fields
              mergedRS.Fields(f.Name) = f.Value
            Next
            rs.MoveNext
          Loop
        End If
        c = c + 1
      Next
     
     
      Set sh = wb.Worksheets.Add
     
      mergedRS.MoveFirst
      r = 1
      c = 1
      For Each f In mergedRS.Fields
        sh.Cells(r, c).Formula = f.Name
        c = c + 1
      Next
     
      r = 2
      Do Until mergedRS.EOF
        c = 1
        For Each f In mergedRS.Fields
          sh.Cells(r, c).Value = f.Value
          c = c + 1
        Next
        r = r + 1
        mergedRS.MoveNext
      Loop
    End Sub
     
    Public Function InCollection(col As Collection, key As String) As Boolean
      Dim var As Variant
      Dim errNumber As Long
     
      InCollection = False
      Set var = Nothing
     
      Err.Clear
      On Error Resume Next
        var = col.Item(key)
        errNumber = CLng(Err.Number)
      On Error GoTo 0
     
      '5 is not in, 0 and 438 represent incollection
      If errNumber = 5 Then ' it is 5 if not in collection
        InCollection = False
      Else
        InCollection = True
      End If
     
    End Sub
    Last edited by TheSmileyCoder; Nov 26 '11, 07:21 PM. Reason: Added [Code] before your code, and [/code] after your code. Please remember to use the tags around your code in the future.
  • Guido Geurs
    Recognized Expert Contributor
    • Oct 2009
    • 767

    #2
    When the dim type not shows automatically or when it gives an error, it means that it is not recognized in VBA.
    You have to inset the Reference: "Microsoft DAO 3.6 object library" with the class "recordset"

    Comment

    • sandy armstrong
      New Member
      • Oct 2011
      • 88

      #3
      Hello Guido, Thanks for the respone. I am having the worst time figuring this out I have tried i think almost everything for the past week I am serious thinking of converting to Access for this because i cannot combine the worksheet and keep the source from the orginal, If a change is made on the orginal then it refelts on the Master copy. I would like to be able to Combine all workbooks in the same folder. I think that my table is all ready in array. I have attached a the workbook is this some thing that can be done
      Attached Files

      Comment

      • Guido Geurs
        Recognized Expert Contributor
        • Oct 2009
        • 767

        #4
        This will copy the sheets from all workbooks in the folder:

        Code:
        Option Explicit
        
        Private Sub Workbook_Open()
        Dim FILEScount As Integer
        Dim WORKBOOKopen As Workbook
        Dim WORKBOOKSidx As Integer
        Dim ARRAYDATA As Variant
        Dim FIRSTblancoROW As String
            '§ Find all files in the folder
            With Application.FileSearch
                .NewSearch
                .SearchSubFolders = False
                .LookIn = ThisWorkbook.Path
                .Execute
                '§ if we found some files to open:
                If .FoundFiles.Count > 0 Then
                    '§ Stop screen flicker of workbooks being opened
                    Application.ScreenUpdating = False
                    '§ Simple loop, opening the workbooks
                    For FILEScount = 1 To .FoundFiles.Count
                        If .FoundFiles(FILEScount) <> ThisWorkbook.FullName Then _
                            Set WORKBOOKopen = Workbooks.Open(.FoundFiles(FILEScount))
                        DoEvents
                    Next FILEScount
                End If
            End With
        '§ Copy sheets
            For WORKBOOKSidx = 1 To Application.Workbooks.Count
                If Application.Workbooks(WORKBOOKSidx).Name <> ThisWorkbook.Name Then
                    Workbooks(WORKBOOKSidx).Sheets(1).Activate
                    Range("A2").Resize(Range("A2").End(xlDown).Row - 1, 32).Select
                    ARRAYDATA = Selection
                    Workbooks(ThisWorkbook.Name).Sheets(1).Activate
                    If Range("A2").End(xlDown).Address = "$A$65536" Then
                        FIRSTblancoROW = "A2" '§ blanco sheet
                    Else
                        FIRSTblancoROW = Range("A2").End(xlDown).Address
                    End If
                    Range(FIRSTblancoROW).Resize(UBound(ARRAYDATA, 1), UBound(ARRAYDATA, 2)) = ARRAYDATA
                End If
            Next
        '§ close workbooks
            For WORKBOOKSidx = Application.Workbooks.Count To 1 Step -1
                If Application.Workbooks(WORKBOOKSidx).Name <> ThisWorkbook.Name Then
                    Application.Workbooks(WORKBOOKSidx).Close SaveChanges:=False
                End If
            Next
        End Sub
        PS:
        This is working in Office 2003!
        Maybe you have to change the condition of finding the files!?
        Attached Files

        Comment

        • sandy armstrong
          New Member
          • Oct 2011
          • 88

          #5
          As soon I opened the file an error message popped up "Object Doeesn't Support this action" and the highlighted line is
          Line 8: "With Application.fil eSearch". I dont know what that means???? Im using 2010 How can I fix that
          Code:
          Private Sub Workbook_Open()
          Dim FILEScount As Integer
          Dim WORKBOOKopen As Workbook
          Dim WORKBOOKSidx As Integer
          Dim ARRAYDATA As Variant
          Dim FIRSTblancoROW As String
              '§ Find all files in the folder
              With Application.FileSearch
                  .NewSearch
                  .SearchSubFolders = False
                  .LookIn = ThisWorkbook.Path
                  .Execute
                  '§ if we found some files to open:
                  If .FoundFiles.Count > 0 Then
                      '§ Stop screen flicker of workbooks being opened
                      Application.ScreenUpdating = False
                      '§ Simple loop, opening the workbooks
                      For FILEScount = 1 To .FoundFiles.Count
                          If .FoundFiles(FILEScount) <> ThisWorkbook.FullName Then _
                              Set WORKBOOKopen = Workbooks.Open(.FoundFiles(FILEScount))
                          DoEvents
                      Next FILEScount
                  End If
              End With
          '§ Copy sheets
              For WORKBOOKSidx = 1 To Application.Workbooks.Count
                  If Application.Workbooks(WORKBOOKSidx).Name <> ThisWorkbook.Name Then
                      Workbooks(WORKBOOKSidx).Sheets(1).Activate
                      Range("A2").Resize(Range("A2").End(xlDown).Row - 1, 32).Select
                      ARRAYDATA = Selection
                      Workbooks(ThisWorkbook.Name).Sheets(1).Activate
                      If Range("A2").End(xlDown).Address = "$A$65536" Then
                          FIRSTblancoROW = "A2" '§ blanco sheet
                      Else
                          FIRSTblancoROW = Range("A2").End(xlDown).Address
                      End If
                      Range(FIRSTblancoROW).Resize(UBound(ARRAYDATA, 1), UBound(ARRAYDATA, 2)) = ARRAYDATA
                  End If
              Next
          '§ close workbooks
              For WORKBOOKSidx = Application.Workbooks.Count To 1 Step -1
                  If Application.Workbooks(WORKBOOKSidx).Name <> ThisWorkbook.Name Then
                      Application.Workbooks(WORKBOOKSidx).Close SaveChanges:=False
                  End If
              Next
          End Sub
          Thanks for helping Appreciated!!!
          Last edited by TheSmileyCoder; Nov 26 '11, 07:25 PM. Reason: Added [Code] tags

          Comment

          • Guido Geurs
            Recognized Expert Contributor
            • Oct 2009
            • 767

            #6
            FileSearch is not supported any more in 2007 or later.
            (I have found a lot of angry people on the net because of this ;D).
            This is a work around with Dir: (is not working for 2003)
            Code:
            Option Explicit
            
            Private Sub Workbook_Open()
            Dim FILEScount As Integer
            Dim WORKBOOKopen As Workbook
            Dim WORKBOOKSidx As Integer
            Dim ARRAYDATA As Variant
            Dim FIRSTblancoROW As String
            Dim FILESstring As String
            Dim FILEname As String
            Dim HOMEfolder As String
            Dim ARRfiles() As String
                HOMEfolder = ThisWorkbook.Path
            '§ Find all files in the folder
                If Right$(ThisWorkbook.Path, 1) <> "\" Then HOMEfolder = ThisWorkbook.Path & "\"
                '§ first file
                FILESstring = Dir(HOMEfolder & "*.xlsm")
                '§ rest of files
                Do
                    FILEname = Dir
                    If FILEname = "" Then Exit Do
                    If FILEname <> ThisWorkbook.Name Then FILESstring = FILESstring & "|" & FILEname
                Loop
                ARRfiles = Split(FILESstring, "|")
                '§ if we found some files to open:
                If UBound(ARRfiles) > 0 Then
                    '§ Stop screen flicker of workbooks being opened
                    Application.ScreenUpdating = False
                    '§ opening the workbooks
                    For FILEScount = LBound(ARRfiles) To UBound(ARRfiles)
                        Set WORKBOOKopen = Workbooks.Open(HOMEfolder & ARRfiles(FILEScount))
                    Next FILEScount
                End If
            '§ Copy sheets
                For WORKBOOKSidx = LBound(ARRfiles) To UBound(ARRfiles)
                    Workbooks(ARRfiles(WORKBOOKSidx)).Sheets(1).Activate
                    Range("A2").Resize(Range("A2").End(xlDown).Row - 1, 32).Select
                    ARRAYDATA = Selection
                    Workbooks(ThisWorkbook.Name).Sheets(1).Activate
                    If Range("A2").End(xlDown).Address = "$A$1048576" Then
                        FIRSTblancoROW = "A2" '§ blanco sheet
                    Else
                        FIRSTblancoROW = Range("A2").End(xlDown).Address
                    End If
                    Range(FIRSTblancoROW).Resize(UBound(ARRAYDATA, 1), UBound(ARRAYDATA, 2)) = ARRAYDATA
                Next
            '§ close workbooks
                For WORKBOOKSidx = Application.Workbooks.Count To 1 Step -1
                    If Application.Workbooks(WORKBOOKSidx).Name <> ThisWorkbook.Name Then
                        Application.Workbooks(WORKBOOKSidx).Close SaveChanges:=False
                    End If
                Next
            '§ ScreenUpdating back on
                Application.ScreenUpdating = True
            End Sub
            Attached Files

            Comment

            • sandy armstrong
              New Member
              • Oct 2011
              • 88

              #7
              Wow thanks this is merged perfectly I am very happy with the result!!! thanks so much Giudo for helping with this. You Made My DAY!!!!! :-) aHH i AM SOO HAPPY

              Comment

              • sandy armstrong
                New Member
                • Oct 2011
                • 88

                #8
                omg!!! thanks Guido for helping me with this it merged perfectly now with no problems at all Does this update everytime i open the document? Thanks so much you Seriously made my day... :-) One question???? How do i get the heading for the first page to come ove as well and thats it

                Comment

                • sandy armstrong
                  New Member
                  • Oct 2011
                  • 88

                  #9
                  hey Guido he is the workbook i was telling you about....
                  Attached Files

                  Comment

                  • Guido Geurs
                    Recognized Expert Contributor
                    • Oct 2009
                    • 767

                    #10
                    Sorry for the error (my mistake) it's not the last line that is not transfered but the next dump who is overwriting the last line of the previous dump.
                    The FIRSTblancoROW must be +1
                    This is the correct code=
                    Code:
                    '§ Copy sheets
                        For WORKBOOKSidx = 1 To Workbooks.Count
                            If Workbooks(WORKBOOKSidx).Name <> ThisWorkbook.Name Then
                                Workbooks(WORKBOOKSidx).Sheets(1).Activate
                                Range("A2").Resize(Range("A2").End(xlDown).Row - 1, 32).Select
                                ARRAYDATA = Selection
                                Workbooks(ThisWorkbook.Name).Sheets(1).Activate
                                If Range("A2").End(xlDown).Address = "$A$1048576" Or _
                                        Range("A2").End(xlDown).Address = "$A$65536" Then
                                    FIRSTblancoROW = 2 '§ blanco sheet
                                Else
                                    FIRSTblancoROW = Range("A2").End(xlDown).Row + 1
                                End If
                                Range("A" & FIRSTblancoROW).Resize(UBound(ARRAYDATA, 1), UBound(ARRAYDATA, 2)) = ARRAYDATA
                            End If
                        Next

                    Comment

                    • Guido Geurs
                      Recognized Expert Contributor
                      • Oct 2009
                      • 767

                      #11
                      This is the code for getting the first row:
                      When you start on a blanco sheet, put the first row in an array and paste it to the sheet.
                      Code:
                      ....
                      '§ Copy sheets
                      Dim WORKBOOKSidx As Integer
                      Dim ARRAYHEADER As Variant
                      Dim ARRAYDATA As Variant
                      Dim FIRSTblancoROW As String
                          For WORKBOOKSidx = 1 To Workbooks.Count
                              If Workbooks(WORKBOOKSidx).Name <> ThisWorkbook.Name Then
                                  '§ FROM workbook
                                  Workbooks(WORKBOOKSidx).Sheets(1).Activate
                                  ARRAYHEADER = Range("A1").Resize(1, Range("A1").End(xlToRight).Column)
                                  ARRAYDATA = Range("A2").Resize(Range("A2").End(xlDown).Row - 1, 32)
                                  '§ TO workbook
                                  Workbooks(ThisWorkbook.Name).Sheets(1).Activate
                                  '§ blanco sheet for version 2003 =>"$A$65536"
                                  '§ blanco sheet for version 2007 =>"$A$1048576"
                                  If Range("A2").End(xlDown).Address = "$A$1048576" Or _
                                          Range("A2").End(xlDown).Address = "$A$65536" Then
                                      FIRSTblancoROW = 2 '§ blanco sheet
                                      '§ paste header
                                      Range("A1").Resize(1, UBound(ARRAYHEADER, 2)) = ARRAYHEADER
                                  Else
                                      FIRSTblancoROW = Range("A2").End(xlDown).Row + 1
                                  End If
                                  Range("A" & FIRSTblancoROW).Resize(UBound(ARRAYDATA, 1), UBound(ARRAYDATA, 2)) = ARRAYDATA
                              End If
                          Next
                      ...

                      Comment

                      • sandy armstrong
                        New Member
                        • Oct 2011
                        • 88

                        #12
                        Thanks Guido for helping me with this sorry for the late respone I was Very busy over the weekend and wasnt able to get to a computer. I was able to use the code u gave me for getting the last row dumped in the merge file and it worked perfectly!!! I also Changed a few lines that allow me to grab the headers but it didnt work correctly because it took the headers from a of the documents in the folder idk how to add the code above to the only i already have without recieving error message

                        Comment

                        • sandy armstrong
                          New Member
                          • Oct 2011
                          • 88

                          #13
                          Hello Guido, I would soo apperciate the help with this i have spent days trying to find out what is the problem. one speadsheet is not merging into the combine worksheet for some reason and i dont know why. so far i have 2 practicelink and file 1. File 1 is not merging into Merge_v3
                          Attached Files

                          Comment

                          • Guido Geurs
                            Recognized Expert Contributor
                            • Oct 2009
                            • 767

                            #14
                            The workbook "File1" has no data in the column "A" so the code with "Range("A2")... ." and ".End(xlDow n)" is not working.
                            A solution is to put data like a string or a number (any data) in the column "A" for each record (row).
                            An other option is to write a tool in which you determin the range in each file to transfer to the workbook "merge".

                            Comment

                            • sandy armstrong
                              New Member
                              • Oct 2011
                              • 88

                              #15
                              OK thanks guido thanks for the fast respone....
                              I like the idea of puting in a range column k to the last row because i really only use the columns.
                              Again thank you!!!!@

                              Comment

                              Working...