Total Pageviews

Tuesday 22 January 2019

Loop through all excel files and save data in thisworkbook

Sub LoopThroughFiles()
    Dim StrFile         As String
    Dim FolderPath      As String
    Dim Wb              As Workbook
    Dim Ws              As Worksheet
 
    '// give full folder path here (remember \ in the end) .. only excel files should be in the folder
    FolderPath = "C:\Users\vds1\Desktop\UIPath\"
 
    '// Loop through all file names..
    StrFile = Dir(FolderPath)
    Do While Len(StrFile) > 0
        '// open every workbook and assign it to variable wb
        Set Wb = Workbooks.Open(FolderPath & StrFile)
        '// loop through every sheet within open workbook - wb
        For Each Ws In Wb.Sheets
            Ws.Select
            '/copy data and paste in current sheet where macro is saved
            Range("A1:Z" & Range("A" & Rows.Count).End(xlUp).Row).Copy ThisWorkbook.ActiveSheet.Range("A" & Rows.Count).End(xlUp).Offset(1, 0)
        Next Ws
        '// Close workbook without saving and set to nothing (memory clean)
        Wb.Close False
        Set Wb = Nothing
     
        '// move to next file
        StrFile = Dir
    Loop
End Sub



-----------------------------------------------------------------


Sub LoopThroughFiles()
    Dim StrFile         As String
    Dim FolderPath      As String
    Dim Wb              As Workbook
    Dim Ws              As Worksheet

    Application.DisplayAlerts = False
 
    '// give full folder path here (remember \ in the end) .. only excel files should be in the folder
    FolderPath = "C:\Users\vds1\Desktop\Temp\2019\"

    '// Loop through all file names..
    StrFile = Dir(FolderPath)
    Do While Len(StrFile) > 0
        '// open every workbook and assign it to variable wb
        Set Wb = Workbooks.Open(FolderPath & StrFile)
        '// loop through every sheet within open workbook - wb
        For Each Ws In Wb.Sheets
            Ws.Select
            '/copy data and paste in current sheet where macro is saved
            Range("A1:Z" & Range("A" & Rows.Count).End(xlUp).Row).Copy ThisWorkbook.Sheets(Ws.Name).Range("A" & Rows.Count).End(xlUp).Offset(1, 0)
        Next Ws
        '// Close workbook without saving and set to nothing (memory clean)
        Wb.Close False
        Set Wb = Nothing
   
        '// move to next file
        StrFile = Dir
    Loop
 
    Application.DisplayAlerts = True
End Sub

No comments:

Post a Comment