Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Sub CopyNewest()
- ActiveWorkbook.Sheets(1).Cells.Delete
- Application.ScreenUpdating = False
- Application.DisplayAlerts = False
- 'dimension variables
- Dim wb, wbn As Workbook, wsDest1 As Worksheet, wsDest2 As Worksheet
- Dim ws1 As Worksheet, Ws2 As Worksheet, i As Long, Pos As Long
- Dim Folder As String, File As String, Path As String
- rw = 1
- 'folder to loop through
- Folder = "C:\" 'change to suit your need
- 'set destination info
- Set wsDest1 = ActiveWorkbook.Sheets(1) 'change to suit your need
- 'Start FileSearch
- With Application.FileSearch
- .LookIn = Folder
- .Filename = "*.xls"
- .FileType = msoFileTypeExcelWorkbooks
- .SearchSubFolders = False
- .Execute
- If .Execute > 0 Then
- 'loop through all found files
- For i = 1 To .FoundFiles.Count
- 'set incidental variables
- Pos = InStrRev(.FoundFiles(i), "\")
- File = Right(.FoundFiles(i), Len(.FoundFiles(i)) - Pos)
- Path = Left(.FoundFiles(i), Pos)
- 'check if workbook is open. if so, set variable to it, else open it
- If IsWbOpen(File) Then
- Set wb = Workbooks(File)
- Else
- Set wb = Workbooks.Open(Path & File)
- End If
- wsDest1.Cells(rw, 1) = File
- wsDest1.Cells(rw, 2) = wb.BuiltinDocumentProperties.Item("Last Save Time")
- rw = rw + 1
- 'set worksheets to copy data from
- 'Set ws1 = wb.Sheets(1)
- 'copy data
- 'ws1.Range("A1:AA1000").Copy 'change the range to copy
- 'With wsDest1.Cells(Rows.Count, 1).End(xlUp).Offset(1)
- '.PasteSpecial xlValues
- 'End With
- wb.Close
- Next i
- End If
- Set wb = Nothing
- Dim mb As Long
- Dim mrng As Range
- Set mrng = wsDest1.Range("b1:b100")
- For mb = 1 To wsDest1.Range("b" & Rows.Count).End(xlUp).Row
- If wsDest1.Cells(mb, 2) = Application.WorksheetFunction.Max(mrng) Then
- Set wb = Workbooks.Open(Path & Cells(mb, 1).Value)
- End If
- Next
- End With
- 'set worksheets to copy data from
- wsDest1.Cells.ClearContents
- Set ws1 = wb.Sheets(1)
- 'copy data
- ws1.Range("A1:AA1000").Copy 'change the range to copy
- With wsDest1.Cells(Rows.Count, 1).End(xlUp).Offset(1)
- .PasteSpecial xlValues
- End With
- wb.Close
- Set wsDest1 = Nothing: Set wsDest2 = Nothing: Set ws1 = Nothing
- Set Ws2 = Nothing: Set wb = Nothing
- [a1].Select
- Application.ScreenUpdating = True
- Application.DisplayAlerts = True
- End Sub
- Function IsWbOpen(wbName As String) As Boolean
- On Error Resume Next
- IsWbOpen = Len(Workbooks(wbName).Name)
- End Function
Advertisement
Add Comment
Please, Sign In to add comment