I have been searching forums and just can't work out the issue with my code. I am very new to macros and I'm sure it's something simple, like some variable not being defined, but I can't figure it out. I am trying to load data from multiple workbooks into a master and really need help please!
Dir for source files: C:\Test Dir\
Dir for Master: C:\Test Dir\Master\
Source filenames differ, but all end in "*FORMATTED.xlsx."
Master filename: "Payroll Master.xlsx"
Source worksheet name = "Loaded Data"
Master worksheet name = "Summary"
All SOURCE data is in A2:J106.
The top row in the source and Master files are column headers and are identical. I am loading all data into the Master file "Summary" worksheet.
My latest error is: "Run-time error '1004': Select method of Range class failed."
on the "Sheets("Loaded Data").Range("A2:J106").Select"
line
This is my current code:
Sub combine_data()
'
Dim MyPath As String
Dim SumPath As String
Dim MyName As String
Dim SumName As String
'Dim MyTemplate As Workbook
'Dim SumTemplate As Workbook
MyPath = "C:\Test Dir\"
SumPath = "C:\Test Dir\Master\"
MyTemplate = "*.xlsx" 'Set the template.
SumTemplate = "Payroll MASTER.xlsx"
MyName = Dir(MyPath & MyTemplate) 'Retrieve the first file
SumName = Dir(SumPath & SumTemplate)
Do While MyName <> ""
Workbooks.Open MyPath & MyName
Sheets("Loaded Data").Range("A2:J106").Select
Selection.Copy
Workbooks.Open SumPath & SumName
Sheets("Summary").Select
Range("A65536").End(xlUp).Offset(1, 0).Activate
Selection.PasteSpecial Paste:=xlPasteValues
Workbooks(MyName).Close SaveChanges:=False 'close
Workbooks(SumName).Close SaveChanges:=True
MyName = Dir 'Get next file
Loop
End Sub
Thank you!
To reduce bugs, you should state
Option Explicit
at the top of the module. You will then be told when using variables that are not declared and you reduce the risk of misspelling the names of variables.You should put the
SumName = Dir(SumPath & SumTemplate)
just before the loop, as theDir
at the end of yourDo While ... Loop
will refer to the LASTDir
that had parameters. When getting past the error with the Select that you describe, you have ran into this problem.Inside your loop, you should refer to each workbook/worksheet individually, to clarify what you are doing (helping yourself for the future).
You are opening and closing the MASTER file for every source-file. You could open it before the Loop and close it after. This will make your script faster.
Here is the code modified with the above comments: