0

Could someone please take a look at my code and tell me what I’m doing wrong? I'm trying to consolidate a group of excel files that are in a folder into a master Excel file. My logic seems right but for some reason, the data is not pasting into the master file from the source files. Thank you all in advance!

Sub ConsolidateMAR()
'
'
'
   Dim lastRow As Long

   Dim MyFolder As String

   Dim myFile As String

   Dim wbkSource As Workbook


   Dim wkbDest As Workbook

   Set wkbDest = Workbooks.Open("C:\Users\xxxxx\Desktop\MAR Test Master File.xlsx")

On Error Resume Next

Application.ScreenUpdating = False



With Application.FileDialog(msoFileDialogFolderPicker)

.Title = "Please select a folder"

.Show

.AllowMultiSelect = False

   If .SelectedItems.Count = 0 Then 'If no folder is selected, abort

MsgBox "You did not select a folder"

      Exit Sub

   End If

MyFolder = .SelectedItems(1) & "\" 'Assign selected folder to MyFolder

End With

myFile = Dir(MyFolder) 'DIR gets the first file of the folder

'Loop through all files in a folder until DIR cannot find anymore

Do While myFile <> “”

   'Opens the file and assigns to the wbkSource variable for future use

   Set wbkSource = Workbooks.Open(FileName:=MyFolder & myFile)

   'Replace the line below with the statements you would want your macro to perform

If Err.Number <> 0 Then
        MsgBox ("Unable to open file " & myFile)
    End If
    On Error GoTo 0


wbkSource.ActiveSheet.Unprotect Password:="adgiam"

Columns.EntireColumn.Hidden = False
    Rows.EntireRow.Hidden = False
    Rows("3:3").Select
    Selection.AutoFilter

    Rows("3:3").Select
    Selection.AutoFilter


    lastRow = wbkSource.ActiveSheet.Cells(Rows.Count, "B").End(xlUp).Row

    Range("A4:W" & lastRow).Select

    Selection.Copy

    Application.DisplayAlerts = False

    erow = wkbDest.Sheets(1).Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row

    wkbDest.ActiveSheet.Paste Destination:=Sheets(1).Range(Cells(erow, 1), Cells(erow, 23))


wbkSource.Close SaveChanges:=False

myFile = Dir 'DIR gets the next file in the folder

Loop

wkbDest.Close SaveChanges:=True

Application.ScreenUpdating = True

MsgBox "Macro has completed! Woot! Woot!"

End Sub
Gary Dorman
  • 375
  • 1
  • 5
  • 16
  • 1
    I have a feeling it's partly (if not completely) due to using `.Select`. It's [recommended to avoid using `.Activate`/`.Select`](http://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba-macros). Also, see how you put the sheet name before `Cells()`? Also do that whenever you use `Rows.Count` or `Columns.Count`, etc. (any range object). – BruceWayne Dec 01 '16 at 15:06
  • Hello i'm not completly understanding. Could you please update my code in regards to your suggestion? Thank you! – Gary Dorman Dec 01 '16 at 15:09
  • 1
    Put `Debug.Print Sheets(1).Parent.Name` in before `wkbDest.ActiveSheet.Paste `. Is it giving the value you expect? – Comintern Dec 01 '16 at 15:09
  • Hello @Comintern. I did what you said and nothing new happened. – Gary Dorman Dec 01 '16 at 15:22
  • What did it output to the immediate window? – Comintern Dec 01 '16 at 15:23
  • (In the VBA editor press `CTRL+G` to open the Immediate Window which is there the Debug printing will show.) Alternatively step through the macro with `F8` and it'll go line by line and you can hover the mouse over the values and see if it's what you expect. I also suggest commenting out the `on error resume next` so you'll see if VBA is throwing an error. Right now, it will suppress any errors. – BruceWayne Dec 01 '16 at 15:39

2 Answers2

0

I had to do something similar, but chose to move the sheets into the new workbook. See So, I have 6 "master" files to then divide into 40 separate files

Solar Mike
  • 7,156
  • 4
  • 17
  • 32
0

Those select statements are pretty dangerous. Try to avoid those and just make a direct reference to the object you want to control.

Something like this should work for you.

Sub Basic_Example_1()
    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

    'Fill in the path\folder where the files are
    MyPath = "C:\Users\Ron\test"

    'Add a slash at the end if the user forget it
    If Right(MyPath, 1) <> "\" Then
        MyPath = MyPath & "\"
    End If

    'If there are no Excel files in the folder exit the sub
    FilesInPath = Dir(MyPath & "*.xl*")
    If FilesInPath = "" Then
        MsgBox "No files found"
        Exit Sub
    End If

    'Fill the array(myFiles)with the list of Excel files in the folder
    Fnum = 0
    Do While FilesInPath <> ""
        Fnum = Fnum + 1
        ReDim Preserve MyFiles(1 To Fnum)
        MyFiles(Fnum) = FilesInPath
        FilesInPath = Dir()
    Loop

    'Change ScreenUpdating, Calculation and EnableEvents
    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 array(myFiles)
    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

                With mybook.Worksheets(1)
                    Set sourceRange = .Range("A1:C1")
                End With

                If Err.Number > 0 Then
                    Err.Clear
                    Set sourceRange = Nothing
                Else
                    'if SourceRange use 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 "Sorry there are not enough rows in the sheet"
                        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 destrange
                        Set destrange = BaseWks.Range("B" & rnum)

                        'we copy the values from the sourceRange to the destrange
                        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 ScreenUpdating, Calculation and EnableEvents
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .Calculation = CalcMode
    End With
End Sub

Also, check out the AddIn below.

http://www.rondebruin.nl/win/addins/rdbmerge.htm

ASH
  • 20,759
  • 19
  • 87
  • 200