+ Reply to Thread
Results 1 to 5 of 5

Copy same range in many excel files and paste into a main file

Hybrid View

  1. #1
    Registered User
    Join Date
    06-19-2013
    Location
    brazil
    MS-Off Ver
    Excel 2007
    Posts
    64

    Copy same range in many excel files and paste into a main file

    Please, I need a little help.
    I want to copy a range from many excel files and paste into another one.

    All the files (with the ranges to be copied) are closed inside a folder, with sequential names .
    The file that will receive the ranges ("Boxx") is in another folder.

    I want to copy the range "B1:S5" and paste in "B1"(in "Boxx").
    Then, the next ranges should be pasted sequentially in B6, B11, B16, etc.

    The closest VBA code I've found and modified is here:

    
    Sub Themissedline()
    
    Dim lCount As Long
    Dim wbResults As Workbook
    Dim wbCodeBook As Workbook
    
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    Application.EnableEvents = False
    
    On Error Resume Next
        Set wbCodeBook = ThisWorkbook
            With Application.FileSearch
            .NewSearch
            'Change path to suit
            .LookIn = "E:\DOWNLOADS\IIII"
            .FileType = msoFileTypeExcelWorkbooks
            'Optional filter with wildcard
            '.Filename = "*AAAA.xls"
            If .Execute > 0 Then 'Workbooks in folder
            For lCount = 1 To .FoundFiles.Count 'Loop through all
            'Open Workbook x and Set a Workbook variable to it
            Set wbResults = Workbooks.Open(Filename:=.FoundFiles(lCount), UpdateLinks:=0)
    
    
    wbResults.Worksheets("Plan1").Range("B1:S5").Copy
    wbCodeBook.Worksheets("Plan1").Range("B1" & Rows.Count).End(xlUp).Offset(1).PasteSpecial xlPasteValues
    Application.CutCopyMode = False
                            
    
                            wbResults.Close SaveChanges:=False
                        Next lCount
                    End If
            End With
    On Error GoTo 0
    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
    Application.EnableEvents = True
    
    End Sub
    What's the missed line??
    Last edited by dualaudio454252; 11-15-2014 at 05:28 PM.

  2. #2
    Forum Expert
    Join Date
    10-09-2012
    Location
    Dallas, Texas
    MS-Off Ver
    MO 2010 & 2013
    Posts
    3,049

    Re: Copy same range in many excel files and paste into a main file

    I modified some code I already had for something similar.

    Sub LoopAllExcelFilesInFolder()
    'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them
    '==============================================
    'Declare Variables
    '==============================================
        Dim wb As Workbook
        Dim myPath As String
        Dim myFile As String
        Dim myExtension As String
        Dim FldrPicker As FileDialog
        Dim LastRow As Long
        Dim SourceRng As String
    
    '==============================================
    'Optimize Macro Speed
    '==============================================
      Application.ScreenUpdating = False
      Application.EnableEvents = False
      Application.Calculation = xlCalculationManual
    
    '==============================================
    'Find Folder and Define Variables
    '==============================================
        SourceRng = "B1:S5" 'Used to define Source Range
        Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
    
        With FldrPicker
          .Title = "Select A Target Folder"
          .AllowMultiSelect = False
            If .Show <> -1 Then GoTo NextCode
            myPath = .SelectedItems(1) & "\"
        End With
    
    'In Case of Cancel
    NextCode:
        myPath = myPath
            If myPath = "" Then
            'Turn these things back on then exit
                Application.ScreenUpdating = True
                Application.EnableEvents = True
                Application.Calculation = xlCalculationAutomatic
                    MsgBox "Nothing Was Selected. Macro will End."
                   Exit Sub
            End If
      
        'Target File Extension (must include wildcard "*")
        myExtension = "*.xls"
        'Target Path with Ending Extention
        myFile = Dir(myPath & myExtension)
        FileCounter = 1
    
    '===================================================================
    'Clear Data tab before begining
    '===================================================================
        ThisWorkbook.Sheets("Data").Range("A1:S1048576").Clear 'Set this range to whatever you need
            'This clears whatever range you need to
            'I assumed you want to keep Row 1 to keep the headers
        LastRow = ThisWorkbook.Worksheets("Data").Cells(Rows.Count, 2).End(xlUp).Row 'Calculates the first Empty row on the data tab for 2nd column
    
    '===================================================================
    'This isnt Necessary, only to use the statusbar to indicate how far along you are
    '===================================================================
        Do While myFile <> ""
               FileCount = FileCount + 1
                myFile = Dir()
            Loop
        myFile = Dir(myPath) ' Resets this to the first file in the folder instead of the last
    
    '==============================================
    'Loop through each Excel file in folder
    '==============================================
      Do While myFile <> ""
        If myFile <> ThisWorkbook.Name Then
            Application.StatusBar = "Importing File [" & FileCounter & " of " & FileCount & "] : " & myFile
            
            'Set variable equal to opened workbook
            Set wb = Workbooks.Open(Filename:=myPath & myFile)
            
            'Append data from workbook
            ThisWorkbook.Worksheets("Data").Range("B" & LastRow & ":S" & LastRow + 4).Value2 = wb.Sheets("Plan1").Range(SourceRng).Value2
            
            'Recalc last row in Thisworkbook
            LastRow = ThisWorkbook.Worksheets("Data").Cells(Rows.Count, 2).End(xlUp).Row + 1
            
            'Close Workbook without Saving
            wb.Close SaveChanges:=False
        
                FileCounter = FileCounter + 1
        
        End If
        
        'Get next file name
          myFile = Dir
      Loop
    '==============================================
    'Message Box when tasks are completed
    '==============================================
      MsgBox "Imported " & FileCount & " Files Succesfully"
    
    '==============================================
    'Reset Macro Optimization Settings
    '==============================================
      Application.StatusBar = False
      Application.ScreenUpdating = True
      Application.EnableEvents = True
      Application.Calculation = xlCalculationAutomatic
      
    End Sub
    Please ensure you mark your thread as Solved once it is. Click here to see how.
    If a post helps, please don't forget to add to our reputation by clicking the star icon in the bottom left-hand corner of a post.

  3. #3
    Registered User
    Join Date
    06-19-2013
    Location
    brazil
    MS-Off Ver
    Excel 2007
    Posts
    64

    Re: Copy same range in many excel files and paste into a main file

    All right, I should have searched inside this forum, but untill now Google kept saying me that there was nothing that could help me anywhere in the web.

    I've read the links bellow:
    http://www.excelforum.com/excel-prog...ster-file.html
    http://www.mrexcel.com/forum/excel-q...ed-folder.html

    That gave the code I've modified now, but I just want to copy and paste like values, so I've glued this:
    .PasteSpecial xlPasteValues
    But it's not working.
    Must say that I'm learning VBA from scratch.
    One last help, please:

    Sub tgr()
        
        Dim rngDest As Range
        Dim oShell As Object
        Dim strFolderPath As String
        Dim strFileName As String
        
        Set oShell = CreateObject("Shell.Application")
        On Error Resume Next
        strFolderPath = oShell.BrowseForFolder(0, "Select a Folder", 0).Self.Path & Application.PathSeparator
        Set oShell = Nothing
        On Error GoTo 0
        If Len(strFolderPath) = 0 Then Exit Sub 'Pressed cancel
        
        Set rngDest = ActiveWorkbook.ActiveSheet.Cells(Rows.Count, "B").End(xlUp).Offset(0)
        strFileName = Dir(strFolderPath & "*.xls")
        
        Application.ScreenUpdating = False
        Do While Len(strFileName) > 0
            With Workbooks.Open(strFolderPath & strFileName)
                If Evaluate("IsRef(CALCULAR!A1)") = True Then
                    rngDest.Value = strFileName
                    .Sheets("CALCULAR").Range("K1:AB5").Copy rngDest.Offset(0)
                    Set rngDest = rngDest.Offset(5).PasteSpecial xlPasteValues
                End If
                .Close False
            End With
            strFileName = Dir
        Loop
        
        Application.ScreenUpdating = True
        
        Set rngDest = Nothing
        
    End Sub

  4. #4
    Registered User
    Join Date
    06-19-2013
    Location
    brazil
    MS-Off Ver
    Excel 2007
    Posts
    64

    Re: Copy same range in many excel files and paste into a main file

    mikeTRON, sorry, I was writing the upper message while you were writing, too.
    Like I said, that code is almost complete.
    I just need to know where to put that ".PasteSpecial xlPasteValues" or so.
    I've tried to use your code, but the other has some advantages.
    Thank you very, very much for your effort, but can you help with that?

  5. #5
    Registered User
    Join Date
    06-19-2013
    Location
    brazil
    MS-Off Ver
    Excel 2007
    Posts
    64

    Re: Copy same range in many excel files and paste into a main file

    This way it's working for me:

    Sub ImportCells()
        
        Dim rngDest As Range
        Dim oShell As Object
        Dim strFolderPath As String
        Dim strFileName As String
        
        Set oShell = CreateObject("Shell.Application")
        On Error Resume Next
        strFolderPath = oShell.BrowseForFolder(0, "Select a Folder", 0).Self.Path & Application.PathSeparator
        Set oShell = Nothing
        On Error GoTo 0
        If Len(strFolderPath) = 0 Then Exit Sub 'Pressed cancel
        
        Set rngDest = ActiveWorkbook.ActiveSheet.Cells(Rows.Count, "B").End(xlUp).Offset(0)
        strFileName = Dir(strFolderPath & "*.xls")
        
        Application.ScreenUpdating = False
        Do While Len(strFileName) > 0
            With Workbooks.Open(strFolderPath & strFileName)
                If Evaluate("IsRef(CALCULAR!A1)") = True Then
                    rngDest.Value = strFileName
                    .Sheets("CALCULAR").Range("K1:AB5").Copy rngDest.Offset(0)
                    Set rngDest = rngDest.Offset(5)
                    
                    
    Application.DisplayAlerts = False
               
               
    'turns paste into paste special > values
    Cells.Select
    Selection.Copy
    Range("A1").Select
    Selection.PasteSpecial Paste:=xlPasteValues
                 
                 
                End If
                .Close False
            End With
            strFileName = Dir
        Loop
        
        
        
        Cells.Select
        'Or Range("A1:S10000").Select
        Selection.Copy
        Range("A1").Select
        Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
            :=False, Transpose:=False
            
            
        Range("A1").Select
    
        ActiveWorkbook.Save
        
        Application.ScreenUpdating = True
        
        Set rngDest = Nothing
        
    End Sub
    Thank you so, so much mikeTRON, you were the only who tried to help me!

+ 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. [SOLVED] Copy/paste Range of worksheets of several files in a folder to a master file
    By mrjinx007 in forum Excel Programming / VBA / Macros
    Replies: 2
    Last Post: 06-18-2013, 01:02 PM
  2. Replies: 0
    Last Post: 04-13-2013, 10:45 AM
  3. Replies: 1
    Last Post: 03-28-2013, 02:49 PM
  4. Merging multiple Excel files into tabs of one excel file without having to copy and paste?
    By BrettRCourtney in forum Excel Programming / VBA / Macros
    Replies: 2
    Last Post: 03-13-2013, 03:43 PM
  5. Copy-Paste Macro of 3 columns from multiple excel files into one summary file
    By jpmaster53 in forum Excel Programming / VBA / Macros
    Replies: 4
    Last Post: 11-15-2012, 07:10 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