Search code examples
excelcopy-pasteworksheet-functionvba

Copy and Paste across Folders in a loop with VBA


I am trying to write a loop that copies and pastes a range of data from one workbook to another. I get stuck with the error 'Select Sheet method not proper' or whatever the error message is. This is what I have so far:

folderpath="insert folder path here"
Filename = Dir(folderPath)
Do While Filename <> ""

Set wb = Workbooks.Open(folderPath & Filename)

wb.Worksheets("Outcomes & Factors Rankings").Select
Range("A3", Range("A3").End(xlDown).Offset(0, 6)).Copy
ThisWorkbook.Worksheets("OutcomeFactorRankings").Select
Range("A1").End(xlDown).Offset(1, 0).Select.Paste

wb.Close

Loop

Solution

  • Try to indent your code, you don't need all those selects in your code, simplify, something like that should solve your problem:

    folderPath = "insert folder path here"
        Filename = Dir(folderPath)
    
        Do While Filename <> ""
            Set wb = Workbooks.Open(folderPath & Filename)
            wb.Worksheets("Outcomes & Factors Rankings").Range("A3", Range("A3").End(xlDown).Offset(0, 6)).Copy
            ThisWorkbook.Worksheets("OutcomeFactorRankings").Range("A1").End(xlDown).Offset(1, 0).Paste
            wb.Close
        Loop