I'm relatively new to VBA and I am trying to create code to copy data from approximately 130 xls files in a user-specified directory and paste it into a master workbook. The workbooks and worksheets in the directory all have unique names.
The data I need to copy are in C2:J2 of each file and need to be pasted into the master sheet starting from A2:H2 and populating the next row down until the end of the files is reached.
I would like to loop through all of the files in the directory.
I have tried multiple variations of code to do this and can't seem to get it. I have been able to get the macro to open the directory and it seems to begin the process but doesn't copy and paste the data into my master worksheet. Here is the directory to my master worksheet and I've pasted the code below.
C:\Users\krist\Desktop\TestModifiedCalculated\Compiled.xlsm\
Thanks so much!!
Sub CompileData()
Dim xRg As Range
Dim xSelItem As Variant
Dim xFileDlg As FileDialog
Dim xFileName, xSheetName, xRgStr As String
Dim xBook, xWorkBook As Workbook
Dim xSheet As Worksheet
On Error Resume Next
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False
xSheetName = "Sheet1"
xRgStr = "C2:J2"
Set xFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
With xFileDlg
If .Show = -1 Then
xSelItem = .SelectedItems.Item(1)
Set xWorkBook = ThisWorkbook
Set xSheet = xWorkBook.Sheets("New Sheet")
If xSheet Is Nothing Then
xWorkBook.Sheets.Add(After:=xWorkBook.Worksheets(xWorkBook.Worksheets.Count)).Name = "New Sheet"
Set xSheet = xWorkBook.Sheets("New Sheet")
End If
xFileName = Dir(xSelItem & "\*.xls", vbNormal)
If xFileName = "" Then Exit Sub
Do Until xFileName = ""
Set xBook = Workbooks.Open(xSelItem & "\" & xFileName)
Set xRg = xBook.Worksheets(xSheetName).Range(xRgStr)
xRg.Copy xSheet.Range("A65536").End(xlUp).Offset(1, 0)
xFileName = Dir()
xBook.Close
Loop
End If
End With
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
on error resume next
to right beforeset xsheet = xworkbook.sheets("New Sheet")
and right after that line add inon error goto 0
to see if it errors anywhere. At a guess the sheet names aren't "Sheet1". – Warcupineon error resume next
right before that line, and right after it buton error goto 0
? that should skip that line and move you into theif
statement where you create it. – Warcupine