+ Reply to Thread
Results 1 to 14 of 14

Macro to copy cells from several files into one file

Hybrid View

  1. #1
    Registered User
    Join Date
    11-28-2012
    Location
    LA
    MS-Off Ver
    Excel 2007
    Posts
    9

    Macro to copy cells from several files into one file

    Hi guys,

    I don’t know much about VBA and wanted to see if by providing me an example with explanation as to what each code does whether I can learn the basics for my needs.

    My goal is to combine data from multiple different Excel files into a single new file. Please see the attached files. This is what I am trying to achieve - copy the data from all individual Excel files contained in a given folder, let’s call it “C:\Combo” folder, Paste the values of that data into a single Excel files.

    Example:
    1. Look in file “Data File 1,” sheet “Full IO”
    2. Copy A20 into cell G2 of “Summary File” sheet “Primary”
    3. Copy C20:C49 into G3:G32 of “Summary File” sheet “Primary”
    4. Copy M20:M49 into G3:G32 of “Summary File” sheet “Secondary”
    5. Move over into the next column and copy the same information from the next Excel file (Data File 2) in the given folder and repeat the loop until all the files are copied

    I know that there are a few example online, but the code is not properly explained and I can’t quickly figure out how it works. Seeing a working example like this should help me truly understand how the coding works.

    I would appreciate your help with the example of the code. I am trying to change the way we manage data in our lab since almost no one is utilizing the power of VBA.

    Thanks.
    Attached Files Attached Files
    Last edited by Excelsius1; 11-30-2012 at 02:36 PM.

  2. #2
    Forum Contributor arlu1201's Avatar
    Join Date
    09-09-2011
    Location
    Bangalore, India
    MS-Off Ver
    Excel 2003 & 2007
    Posts
    19,166

    Re: Macro to copy cells from several files into one file

    These steps
    2. Copy A20 into cell G2 of “Summary File” sheet “Primary”
    3. Copy C20:C49 into G3:G32 of “Summary File” sheet “Primary”
    4. Copy M20:M49 into G3:G32 of “Summary File” sheet “Secondary”
    do not match your Summary file. The data does not match at all. Can you please check again.
    If I have helped, Don't forget to add to my reputation (click on the star below the post)
    Don't forget to mark threads as "Solved" (Thread Tools->Mark thread as Solved)
    Use code tags when posting your VBA code: [code] Your code here [/code]

  3. #3
    Registered User
    Join Date
    11-28-2012
    Location
    LA
    MS-Off Ver
    Excel 2007
    Posts
    9

    Re: Macro to copy cells from several files into one file

    Quote Originally Posted by arlu1201 View Post
    These steps do not match your Summary file. The data does not match at all. Can you please check again.
    I know the cells in the summary file are not the same ones as I am copying from - that's the idea. The data is going to be organized differently in the new summary sheet. But this shouldn't matter I guess since it's just a matter of pasting the range into VBA, which can be anything. I just want to see how the coding is done.

  4. #4
    Forum Guru JosephP's Avatar
    Join Date
    03-27-2012
    Location
    Ut
    MS-Off Ver
    2003/10
    Posts
    7,328

    Re: Macro to copy cells from several files into one file

    I'm afraid your post does not comply with Rule 8 of our Forum RULES. Cross-posting is when you post the same question in other forums on the web. You'll find people are disinclined to respond to cross-posts because they may be wasting their time solving a problem that has been solved elsewhere. We prefer that you not cross-post at all, but if you do (and it's unlikely to go unnoticed), you MUST provide a link (copy the url from the address bar in your browser)to the cross-post. Expect cross-posts without a link to be closed a message will be posted by the moderator explaining why. We are here to help so help us to help you!

    Read this to understand why we ask you to do this, and then please edit your first post to include links to any and all cross-posts in any other forums (not just this site).
    Josie

    if at first you don't succeed try doing it the way your wife told you to

  5. #5
    Registered User
    Join Date
    11-28-2012
    Location
    LA
    MS-Off Ver
    Excel 2007
    Posts
    9

    Re: Macro to copy cells from several files into one file

    Ok, changed.

  6. #6
    Registered User
    Join Date
    11-28-2012
    Location
    LA
    MS-Off Ver
    Excel 2007
    Posts
    9

    Re: Macro to copy cells from several files into one file

    I think people are unwilling to help due to cross posting. I haven't received a single response in any of the forums. If anyone can still help, great. Otherwise, I will request the mods to delete this thread by the end of today and maybe start from scratch in one forum. Didn't know this is such an issue.

  7. #7
    Forum Guru JosephP's Avatar
    Join Date
    03-27-2012
    Location
    Ut
    MS-Off Ver
    2003/10
    Posts
    7,328

    Re: Macro to copy cells from several files into one file

    I reckon it's more that your question is a little vague and the sample files don't help if they don't match your request
    as an idea
    dim n as long
    dim vBooks
    dim wbSummary as workbook
    dim wbSource as workbook
    
    set wbsummary = workbooks("Summary File.xlsx")
    ' array of workbook names
    vBooks = array("Data file 1.xlsx", "Data file 2.xlsx","Data file 3.xlsx","Data file 4.xlsx")
    ' loop through array
    for n = lbound(vbooks) to ubound(vbooks)
       ' set reference to workbook
       set wbsource = workbooks(vbooks(n))
       with wbsummary.sheets("Primary")
          ' value of n starts at 0 and increments with each loop so the paste moves across columns
          .range("G2").offset(, n).value = wbsource.sheets("File IO").range("A20").value
          .range("G3:G32").offset(, n).value = wbsource.sheets("File IO").range("C20:C49").value
       end with
       wbsummary.sheets("Secondary").range("G3:G32").offset(, n).value = wbsource.sheets("File IO").range("m20:m49").value
    next n

  8. #8
    Registered User
    Join Date
    11-28-2012
    Location
    LA
    MS-Off Ver
    Excel 2007
    Posts
    9

    Re: Macro to copy cells from several files into one file

    Well, if something is not clear, I can explain. I tried to understand the code you wrote. So it seems you're using dim to define variables. I don't understand everything though. For example, you have defined an array of files, but my goal is not to define them, but to use all excel files consecutively in a given folder path. If I have over 100 files, creating an array would not be feasible if I have to name each file.

    Let's forget about the attachments. The core of my question is this:

    Let's say I have a file called "DataFile1.xlsx" that has a sheet called "DataSheet." I want to create a macro that will copy cells A12:A15 from that sheet into another file called "Summary.xlsx" in the sheet of "SummarySheet" and cells B13:B16.

    What would be the standalone code for that?

    Now, I want to take that same code and create a loop that will do the exact same procedure for every file in a folder called "DataFolder" and copy them into the summary sheet in the next column, the next column, .... until the files run out.

    PS: I have submitted a request to delete all the other cross posts.
    Last edited by Excelsius1; 11-30-2012 at 02:36 PM.

  9. #9
    Forum Guru JosephP's Avatar
    Join Date
    03-27-2012
    Location
    Ut
    MS-Off Ver
    2003/10
    Posts
    7,328

    Re: Macro to copy cells from several files into one file

    the code I gave shows how to get the values from one sheet to another-all you need to change is the array part so that it loops through a folder, or create a function to return an array of file names from a folder. I'm on a deadline at the moment so I can't help with that part right now but the Dir function will help you ;-)

  10. #10
    Registered User
    Join Date
    11-28-2012
    Location
    LA
    MS-Off Ver
    Excel 2007
    Posts
    9

    Re: Macro to copy cells from several files into one file

    I keep getting a compile error using this code. Am I doing something wrong?
    Sub Test1()
    '
    ' Test1 Macro
    Dim n As Long
    Dim vBooks
    Dim wbSummary As Workbook
    Dim wbSource As Workbook
    
    set wbsummary = workbooks(Summary File.xlsm)
    ' array of workbook names
    vBooks = array(Data file 1.xlsx, Data file 2.xlsx,Data file 3.xlsx,Data file 4.xlsx)
    ' loop through array
    For n = LBound(vBooks) To UBound(vBooks)
       ' set reference to workbook
       Set wbSource = Workbooks(vBooks(n))
       With wbSummary.Sheets(Primary)
          ' value of n starts at 0 and increments with each loop so the paste moves across columns
          .range(G2).offset(, n).value = wbsource.sheets(File IO).range(A20).value
          .range(G3G32).offset(, n).value = wbsource.sheets(File IO).range(C20C49).value
       End With
       wbsummary.sheets(Secondary).range(G3G32).offset(, n).value = wbsource.sheets(File IO).range(m20m49).value
    Next n
    End Sub

  11. #11
    Forum Guru JosephP's Avatar
    Join Date
    03-27-2012
    Location
    Ut
    MS-Off Ver
    2003/10
    Posts
    7,328

    Re: Macro to copy cells from several files into one file

    you need quotes around the file names in the array statement
    vBooks = array("Data file 1.xlsx", "Data file 2.xlsx", "Data file 3.xlsx","Data file 4.xlsx")

  12. #12
    Registered User
    Join Date
    11-28-2012
    Location
    LA
    MS-Off Ver
    Excel 2007
    Posts
    9

    Re: Macro to copy cells from several files into one file

    Thanks. There were some other issues too that I fixed and figured out how the code works. Some of the simplest things that can mess up a code and then it takes so long to find what's up. I remember again exactly why I quit my programming path after learning the basics of IDL! Except this time I am doing this for myself and need it, how ironic.

    If you, or anyone has the time to help me a bit with that dir function so I can create a loop that will automatically go through all the excel files in a folder without having to have them all open (like this array code requires now), it would be great.

    PS: I also stumbled upon RDBMerge addon: http://www.rondebruin.nl/merge.htm. Posting here to help others who might just be satisfied with it. It's a workable solution, but in my case I want to write the code myself and attach it customized to each summary sheet. Still, kudos to that guy for creating a nice addon like that. But good luck figuring out the long **** code.

  13. #13
    Valued Forum Contributor
    Join Date
    11-15-2008
    Location
    ph
    MS-Off Ver
    2007/2010/2016
    Posts
    479

    Re: Macro to copy cells from several files into one file

    Hi -

    This code will give you the basic start, this code should be placed in your summary file and outside in your datafile folder
    Sub consolidateFiles()
    Dim f As Object
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    Application.EnableEvents = False
    With CreateObject("Scripting.FileSystemObject")
    Set f = .GetFolder("E:\DataFolder")
        For Each file In f.Files
            Select Case file.Name
                Case "DataFile1.xlsx"
                    Set nb = Workbooks.Open(file)
                    nb.Sheets("DataSheet").Range("a12:a15").Copy Sheets("summarysheet").Range("b13")
                    nb.Close False
                case "your other filename"
                    nb.Sheets("your other sheet name").Range("a12:a15").Copy Sheets("summarysheet").Range("b13")
                    nb.close false
                'etc.etc
            End Select
        Next
    Set f = Nothing:set nb=nothing
    End With
    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
    Application.EnableEvents = True
    End Sub
    Regards,
    Event

  14. #14
    Registered User
    Join Date
    11-28-2012
    Location
    LA
    MS-Off Ver
    Excel 2007
    Posts
    9

    Re: Macro to copy cells from several files into one file

    Thanks for the code. I've been trying to figure it out, but I now see that this code again requires one to write down all the names of the files, which is not feasible when there are close to a hundred files. I am pasting a code I found online that I think is what I need, but it's long and harder to understand, so I'm trying to decode it still. A few questions:

    What is the purpose of using a module? Can't I just paste my macros into "ThisWorkbook" in VBA instead of a module? Also, how do I put together several macros so they run as one code? For example, if one code is what was original posted Joseph and then I want to combine it with the loop that runs though all the folders, can I have them as separate subs that run at the same time?

    Here is the code that I found:

    Sub MergeAllWorkbooks()
        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
    
        ' Change this to the path\folder location of your files.
        MyPath = "C:\test"
    
        ' Add a slash at the end of the path if needed.
        If Right(MyPath, 1) <> "\" Then
            MyPath = MyPath & "\"
        End If
    
        ' If there are no Excel files in the folder, exit.
        FilesInPath = Dir(MyPath & "*.xl*")
        If FilesInPath = "" Then
            MsgBox "No files found"
            Exit Sub
        End If
    
        ' Fill the myFiles array with the list of Excel files
        ' in the search folder.
        FNum = 0
        Do While FilesInPath <> ""
            FNum = FNum + 1
            ReDim Preserve MyFiles(1 To FNum)
            MyFiles(FNum) = FilesInPath
            FilesInPath = Dir()
        Loop
    
        ' Set various application properties.
        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 myFiles array.
        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
    
                    ' Change this range to fit your own needs.
                    With mybook.Worksheets(1)
                        Set sourceRange = .Range("A1:A10")
                    End With
    
                    If Err.Number > 0 Then
                        Err.Clear
                        Set sourceRange = Nothing
                    Else
                        ' If source range uses 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 "There are not enough rows in the target worksheet."
                            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 destination range.
                            Set destrange = BaseWks.Range("B" & rnum)
    
                            ' Copy the values from the source range
                            ' to the destination range.
                            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 the application properties.
        With Application
            .ScreenUpdating = True
            .EnableEvents = True
            .Calculation = CalcMode
        End With
    End Sub
    Some of the things I don't understand are these:
        ' Set various application properties.
        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
    I'm not sure what that adding workbook feature is or what is the purpose of calcmode.

    More importantly, this is the other crucial part of the code:

                            ' Copy the values from the source range
                            ' to the destination range.
                            With sourceRange
                                Set destrange = destrange. _
                                                Resize(.Rows.Count, .Columns.Count)
                            End With
                            destrange.Value = sourceRange.Value
    
                            rnum = rnum + SourceRcount
    I'm not sure how I can modify this to basically say exactly where I want the copied data to be pasted in the destination file - let's say I want to copy the A1:10 from source (which is already in this code) and paste it to B1:B10, which I am not sure how to do.

+ 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