Sub datacopyAll()
Application.ScreenUpdating = False
Set listSht = ThisWorkbook.Sheets("Sheet3") 'destination sheet
Dim WkBArray()
WkBArray = Array("BookTest.xls", "BookTest2.xls") 'list all the workboks to be used
LastCol2 = listSht.Cells.Find("*", Cells(Rows.Count, Columns.Count), SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
LastRow = listSht.Cells.Find("*", Cells(Rows.Count, Columns.Count), SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Row
listSht.Range(listSht.Cells(1, 2), listSht.Cells(LastRow, LastCol2)).ClearContents
For Each wkBfileName In WkBArray 'loop through all listed workbooks
Set wkB = Workbooks.Open(wkBfileName)
For Each wkS In wkB.Worksheets 'loop through all worksheets in opened workbook.
Set DataSht = wkS
LastCol = DataSht.Cells.Find("*", Cells(Rows.Count, Columns.Count), SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
For Col = 2 To LastCol - 2 'loops through all columns in source sheet from column B to the last column used
LastCol2 = listSht.Cells.Find("*", Cells(Rows.Count, Columns.Count), SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column 'finds last used column in destination
If DataSht.Cells(1, Col).Value <> "" Then 'test for an empty column, assumes any column with empty cell in row 1 is empty
DataSht.Columns(Col).Copy 'copies whole column
listSht.Columns(LastCol2 + 1).PasteSpecial (xlPasteValuesAndNumberFormats) 'pastes numbers and formats to the destination sheet
End If
Next Col
Next wkS
Application.CutCopyMode = False
wkB.Close
Next wkBfileName
LastCol2 = listSht.Cells.Find("*", Cells(Rows.Count, Columns.Count), SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
LastRow = listSht.Cells.Find("*", Cells(Rows.Count, Columns.Count), SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Row
With listSht
If LastCol2 <> 2 Then ' checks whether a sort is neded, if so sorts by date header
.Range(.Cells(1, 2), .Cells(LastRow, LastCol2)).Sort Key1:=Range("B1"), Order1:=xlAscending, Header:=xlGuess, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlLeftToRight, _
DataOption1:=xlSortNormal
End If
If .Cells(1, LastCol2).Value = "YTD" Then 'checks whether YTD header is present
i = 0
j = -1
Else 'if not present creates it
.Cells(1, LastCol2 + 1).Value = "YTD"
i = 1
j = 0
End If
'updates YTD formulas
.Range(.Cells(2, LastCol2 + i), .Cells(LastRow, LastCol2 + i)).FormulaR1C1 = "=SUM(R" & Row & "C2:R" & Row & "C" & LastCol2 + j & ")"
End With
ThisWorkbook.Save 'saves source workbook
Application.ScreenUpdating = True 'turns screen updating back on
ThisWorkbook.Close False 'closes source workbook
End Sub