Zac Paul Kueffer
Zac Paul Kueffer

Reputation: 11

I cannot figure out how to take data from multiple workbooks and put them on a master sheet. 20 files that need to be added to the master sheet

Sub copyDataFromMultipleWorkbooksIntoMaster()

Dim FolderPath As String, Filepath As String, FileName As String

FolderPath = "S:\test\" '""

Filepath = FolderPath & "*.xls*"

FileName = Dir(Filepath)

Dim lastrow As Long, lastcolumn As Long

Do While FileName <> ""
Workbooks.Open (FolderPath & FileName)


'ActiveWorkbooks.Sheets(Array("sheet2")).Select




lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
lastcolumn = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Range(Cells(2, 1), Cells(lastrow, lastcolumn)).Copy
Application.DisplayAlerts = False


erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
ActiveSheet.Paste Destination:=Worksheets("sheet1").Range(Cells(erow,     1), Cells(erow, 7))
Application.CutCopyMode = False
'ActiveWorkbook.Close
FileName = Dir

Loop



 End Sub

When this code is inserted it seems to be copying on the workbook that the data should be pasted on. So, in the end nothing gets pasted to the Mastersheet workbook. Also when it gets to the Activesheet.Paste a Run-Time 1004 pops up. And if I have the Activeworkbook.close open then it closes the document that should remain open. I need some help....

Upvotes: 1

Views: 131

Answers (2)

user4039065
user4039065

Reputation:

Perhaps this rewrite will get you on the right track.

Option Explicit

Sub copyDataFromMultipleWorkbooksIntoMaster()

    Dim folderPath As String, filepath As String, fileName As String
    Dim lastRow As Long, lastColumn As Long, ws1 As Worksheet

    Set ws1 = ActiveWorkbook.Worksheets(1)
    folderPath = "S:\test\"
    filepath = folderPath & "*.xls*"
    fileName = Dir(filepath)        

    Do While fileName <> ""
        With Workbooks.Open(folderPath & fileName, ReadOnly:=True)

            With .Worksheets(1).Cells(1, 1).CurrentRegion
                .Cells.Copy _
                  Destination:=ws1.Cells(ws1.Rows.Count, "A").End(xlUp).Offset(1, 0)
            End With
            .Close SaveChanges:=False
        End With
        fileName = Dir
    Loop

End Sub

This is intended to be run when the workbook with the Master worksheet is active and the Master worksheet is the first worksheet in the workbook.

Upvotes: 1

ASH
ASH

Reputation: 20302

This question comes up ALL THE TIME. Lol. Ok, as always, try the script below.

Merge a range from all workbooks in a folder (below each other)

There are a few things you must change before you can run the code

Fill in the path to the folder MyPath = "C:\Users\Ron\test"

I use the first worksheet of each workbook in my example (index 1). Change the worksheet index or fill in a sheet name: mybook.Worksheets("YourSheetName"). And change the range A1:C1 to your range

With mybook.Worksheets(1)
    Set SourceRange = .Range("A1:C1")
End With

If you want to copy all cells from the worksheet or from A2 till the last cell on the worksheet.Then replace the code above with this

With mybook.Worksheets(1)
    FirstCell = "A2"
    Set SourceRange = .Range(FirstCell & ":" & RDB_Last(3, .Cells))
    'Test if the row of the last cell >= then the row of the FirstCell
    If RDB_Last(1, .Cells) < .Range(FirstCell).Row Then
         Set SourceRange = Nothing
    End If
End With

Add also this dim line at the top of the macro Dim FirstCell As String

Note: the code above use the function RDB_Last, copy this function also in your code module if you use it. You find the function in the last section of this page.

Fill in the first cell here and the code will find the last cell on the worksheet for you. FirstCell = "A2"

Sub Basic_Example_1()
    Dim MyPath As String, FilesInPath As String
    Dim MyFiles() As String
    Dim SourceRcount As Long, Fnum As Long
    Dim mybook As Workbook, BaseWks As Worksheet
    Dim sourceRange As Range, destrange As Range
    Dim rnum As Long, CalcMode As Long

    'Fill in the path\folder where the files are
    MyPath = "C:\Users\Ron\test"

    'Add a slash at the end if the user forget it
    If Right(MyPath, 1) <> "\" Then
        MyPath = MyPath & "\"
    End If

    'If there are no Excel files in the folder exit the sub
    FilesInPath = Dir(MyPath & "*.xl*")
    If FilesInPath = "" Then
        MsgBox "No files found"
        Exit Sub
    End If

    'Fill the array(myFiles)with the list of Excel files in the folder
    Fnum = 0
    Do While FilesInPath <> ""
        Fnum = Fnum + 1
        ReDim Preserve MyFiles(1 To Fnum)
        MyFiles(Fnum) = FilesInPath
        FilesInPath = Dir()
    Loop

    'Change ScreenUpdating, Calculation and EnableEvents
    With Application
        CalcMode = .Calculation
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    'Add a new workbook with one sheet
    Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
    rnum = 1

    'Loop through all files in the array(myFiles)
    If Fnum > 0 Then
        For Fnum = LBound(MyFiles) To UBound(MyFiles)
            Set mybook = Nothing
            On Error Resume Next
            Set mybook = Workbooks.Open(MyPath & MyFiles(Fnum))
            On Error GoTo 0

            If Not mybook Is Nothing Then

                On Error Resume Next

                With mybook.Worksheets(1)
                    Set sourceRange = .Range("A1:C1")
                End With

                If Err.Number > 0 Then
                    Err.Clear
                    Set sourceRange = Nothing
                Else
                    'if SourceRange use all columns then skip this file
                    If sourceRange.Columns.Count >= BaseWks.Columns.Count Then
                        Set sourceRange = Nothing
                    End If
                End If
                On Error GoTo 0

                If Not sourceRange Is Nothing Then

                    SourceRcount = sourceRange.Rows.Count

                    If rnum + SourceRcount >= BaseWks.Rows.Count Then
                        MsgBox "Sorry there are not enough rows in the sheet"
                        BaseWks.Columns.AutoFit
                        mybook.Close savechanges:=False
                        GoTo ExitTheSub
                    Else

                        'Copy the file name in column A
                        With sourceRange
                            BaseWks.cells(rnum, "A"). _
                                    Resize(.Rows.Count).Value = MyFiles(Fnum)
                        End With

                        'Set the destrange
                        Set destrange = BaseWks.Range("B" & rnum)

                        'we copy the values from the sourceRange to the destrange
                        With sourceRange
                            Set destrange = destrange. _
                                            Resize(.Rows.Count, .Columns.Count)
                        End With
                        destrange.Value = sourceRange.Value

                        rnum = rnum + SourceRcount
                    End If
                End If
                mybook.Close savechanges:=False
            End If

        Next Fnum
        BaseWks.Columns.AutoFit
    End If

ExitTheSub:
    'Restore ScreenUpdating, Calculation and EnableEvents
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .Calculation = CalcMode
    End With
End Sub

Good luck!!

Upvotes: 1

Related Questions