0

Before starting to explain my problem, sorry for the messy code, I'm still a beginner in VBA and thank you for your help in advance.

So what I'm trying to do is getting a way of copying the contents of some workbooks in a folder to my master file, which is kinda like a data base. The trick here is that I need the 2 sheets from the file to be copied into the 1st sheet of my master file.

In the mean time and looking through a lot of posts, like this one, VBA Loop through files in folder and copy/paste to master file, I came up with this code:

Option Explicit

Sub AllFiles()

Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.EnableCancelKey = xlDisabled
Application.ScreenUpdating = False

Dim folderPath As String
Dim Filename As String
Dim wb As Workbook
Dim Masterwb  As Workbook
Dim sh As Worksheet
Dim NewSht As Worksheet
Dim FindRng As Range
Dim PasteRow As Long
Dim i As Integer

' set master workbook
Set Masterwb = ThisWorkbook



folderPath = Sheets("teste").Range("A1").Value 'contains folder path

If Right(folderPath, 1) <> "\" Then folderPath = folderPath & "\"

For i = 1 To Sheets("leit_func").Range("S2")
Filename = Dir(folderPath & Sheets("teste").Range("A3"))

Do While Filename <> ""
    Set wb = Workbooks.Open(folderPath & Filename)

    If Len(wb.Name) > 35 Then
        MsgBox "Sheet's name can be up to 31 characters long, shorten the Excel file name"
        wb.Close False
        GoTo Exit_Loop
    Else
        ' add a new sheet with the file's name (remove the extension)
        '-------------------------------------------------------------------------------------------
        'Set NewSht = Masterwb.Worksheets.Add(After:=Masterwb.Worksheets(1))
        'NewSht.Name = Replace(wb.Name, ".xlsx", "")
        '-------------------------------------------------------------------------------------------

    Set NewSht = ThisWorkbook.Sheets(i)



    End If

    ' loop through all sheets in opened wb

    For Each sh In wb.Worksheets

        ' get the first empty row in the new sheet
        Set FindRng = NewSht.Cells.Find(What:="*", Lookat:=xlPart, LookIn:=xlFormulas, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False)
        If Not FindRng Is Nothing Then ' If find is successful
            PasteRow = FindRng.Row + 1
        Else ' find was unsuccessfull > new empty sheet, should paste at the first row
            PasteRow = 1
        End If
        sh.UsedRange.Copy
        NewSht.Range("A" & PasteRow).PasteSpecial xlPasteValues
        'NewSht.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:=xlNone, SkipBlanks:= _
                False, Transpose:=False

    Next sh
    wb.Close False
Exit_Loop:
    Set wb = Nothing
    Filename = Dir()
Loop

 Next i


Application.ScreenUpdating = True
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False
End Sub

With this code I can paste the info in different sheets, but the problem is that it's getting the contents from all the files in the folder, and I want file 1 in sheet 1, file 2 in sheet 2, and so on.

I think my problem has something to do with the placement of my For cycle for the sheets, but I'm not exactly sure.

Thank you!

braX
  • 11,506
  • 5
  • 20
  • 33
  • Do you want the content or also formatting and formulas and so on? – Mono Feb 08 '18 at 14:33
  • Just content is enough for this case. – RafaelCarrilho Feb 08 '18 at 14:41
  • Ok, well you got an kind of sufficient answer now anyway. I just wanted to discourage you from using copy and paste functions. You can assign Range.Values directly or with arrays. – Mono Feb 08 '18 at 15:45
  • Yes, I just used those functions because my experience with VBA is still very limited so I used what I knew it could work for me. Thank you for the advice! – RafaelCarrilho Feb 08 '18 at 15:50

1 Answers1

0

Here is a copy/paste from a script library i keep. It is a rough example of how to loop through files in a directory and copy and paste each sheet to a new sheet in the master workbook. I have included a section that shows how to append to the end of a range as well. Both can be useful. Note that i use arrays to move data as its easier and faster.

Public Sub this()
    Dim path As String, fileName As String, shtName As String
    Dim sheet As Worksheet, thisWB As Workbook, thatWB As Workbook
    Dim arr() As Variant
    Dim rowC As Long, colC As Long, mrowC As Long, mColC As Long
    path = "your path to directory" & "\"
    fileName = Dir(path & "*.xl??")
    Set thisWB = ThisWorkbook
    Do While Len(fileName) > 0
        Set thatWB = Workbooks.Open(path & fileName, True, True)
        For Each sheet In thatWB.Sheets
            shtName = Left(Mid(fileName, 1, InStrRev(fileName, ".") - 1), 30)
            thisWB.ActiveSheet.Name = shtName
            mrowC = thisWB.Sheets(shtName).UsedRange.Rows.Count
            mColC = thisWB.Sheets(shtName).UsedRange.Columns.Count
            arr = sheet.UsedRange
            rowC = sheet.UsedRange.Rows.Count
            colC = sheet.UsedRange.Columns.Count
            thisWB.Sheets(shtName).Range(thisWB.Sheets(shtName).Cells(mrowC + 1, 1), thisWB.Sheets(shtName).Cells(mrowC + 1 + rowC, colC)).Value2 = arr
        Next sheet
        thatWB.Close False
        fileName = Dir()
        thisWB.Sheets.Add After:=Worksheets(Worksheets.Count)
    Loop
End Sub 
Doug Coats
  • 6,255
  • 9
  • 27
  • 49
  • I'm having some trouble running this code and I don't know if it serves my needs, because I don't see how it can copy and paste in different sheets if I need to insert my sheet name at the end, more specifically, after the "'append to end of range method" line. – RafaelCarrilho Feb 08 '18 at 14:54
  • Well the point was to include both methods. Delete the one you do not need. If you need the new sheet ot have the filename of the file you got it from use the line i added. – Doug Coats Feb 08 '18 at 14:57
  • I did change it up for you :) – Doug Coats Feb 08 '18 at 15:09
  • I have replaced the path with my own and ran the sub and nothng happens. It doesn't even give me a error back. I think I may be doing something wrong here. I used the last code you updated. – RafaelCarrilho Feb 08 '18 at 15:09
  • I'm sorry if I'm doing a dumb mistake, but I never really worked with arrays before. – RafaelCarrilho Feb 08 '18 at 15:28
  • Sorry for the confusion - ended up having to fix it. – Doug Coats Feb 08 '18 at 15:38
  • Dont worry about it either - turns out that I made a mistake :D – Doug Coats Feb 08 '18 at 15:39
  • I would just hint that the normal UsedRanged function of a worksheet might give wrong results sometime. For example when the A1 is empty or you have formatted stuff with no content or you only deleted content. – Mono Feb 08 '18 at 15:47
  • Alright, now it worked but maybe I wasn't explicit enough when talking about my issue. This code serves creates new sheets, and my goal is to paste de data from the other files into my existing sheets. In this case, I wanted it to be pasted in my first 15 sheets. I'm gonna try and change the bit that is creating new sheets and I'll get back to you. Thank you for your help! – RafaelCarrilho Feb 08 '18 at 15:48
  • Eventually theyl;l give us the option to go to chat and when it pops up ill leave it up :) – Doug Coats Feb 08 '18 at 15:49
  • And yes @Mono I am aware of that but its a safe assumption in this context to use it though I guess we could explicity spell it out another way. – Doug Coats Feb 08 '18 at 15:50