krcha

Untitled

May 11th, 2015
320
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.92 KB | None | 0 0
  1. Sub CopyNewest()
  2. ActiveWorkbook.Sheets(1).Cells.Delete
  3. Application.ScreenUpdating = False
  4. Application.DisplayAlerts = False
  5.  
  6. 'dimension variables
  7. Dim wb, wbn As Workbook, wsDest1 As Worksheet, wsDest2 As Worksheet
  8. Dim ws1 As Worksheet, Ws2 As Worksheet, i As Long, Pos As Long
  9. Dim Folder As String, File As String, Path As String
  10. rw = 1
  11. 'folder to loop through
  12. Folder = "C:\" 'change to suit your need
  13. 'set destination info
  14. Set wsDest1 = ActiveWorkbook.Sheets(1) 'change to suit your need
  15. 'Start FileSearch
  16. With Application.FileSearch
  17. .LookIn = Folder
  18. .Filename = "*.xls"
  19. .FileType = msoFileTypeExcelWorkbooks
  20. .SearchSubFolders = False
  21. .Execute
  22. If .Execute > 0 Then
  23. 'loop through all found files
  24. For i = 1 To .FoundFiles.Count
  25. 'set incidental variables
  26. Pos = InStrRev(.FoundFiles(i), "\")
  27. File = Right(.FoundFiles(i), Len(.FoundFiles(i)) - Pos)
  28. Path = Left(.FoundFiles(i), Pos)
  29. 'check if workbook is open. if so, set variable to it, else open it
  30. If IsWbOpen(File) Then
  31. Set wb = Workbooks(File)
  32. Else
  33. Set wb = Workbooks.Open(Path & File)
  34. End If
  35. wsDest1.Cells(rw, 1) = File
  36. wsDest1.Cells(rw, 2) = wb.BuiltinDocumentProperties.Item("Last Save Time")
  37. rw = rw + 1
  38. 'set worksheets to copy data from
  39. 'Set ws1 = wb.Sheets(1)
  40. 'copy data
  41. 'ws1.Range("A1:AA1000").Copy 'change the range to copy
  42. 'With wsDest1.Cells(Rows.Count, 1).End(xlUp).Offset(1)
  43. '.PasteSpecial xlValues
  44. 'End With
  45. wb.Close
  46. Next i
  47. End If
  48.  
  49. Set wb = Nothing
  50. Dim mb As Long
  51. Dim mrng As Range
  52. Set mrng = wsDest1.Range("b1:b100")
  53. For mb = 1 To wsDest1.Range("b" & Rows.Count).End(xlUp).Row
  54. If wsDest1.Cells(mb, 2) = Application.WorksheetFunction.Max(mrng) Then
  55. Set wb = Workbooks.Open(Path & Cells(mb, 1).Value)
  56. End If
  57. Next
  58. End With
  59. 'set worksheets to copy data from
  60. wsDest1.Cells.ClearContents
  61. Set ws1 = wb.Sheets(1)
  62. 'copy data
  63. ws1.Range("A1:AA1000").Copy 'change the range to copy
  64. With wsDest1.Cells(Rows.Count, 1).End(xlUp).Offset(1)
  65. .PasteSpecial xlValues
  66. End With
  67. wb.Close
  68.  
  69. Set wsDest1 = Nothing: Set wsDest2 = Nothing: Set ws1 = Nothing
  70. Set Ws2 = Nothing: Set wb = Nothing
  71. [a1].Select
  72. Application.ScreenUpdating = True
  73. Application.DisplayAlerts = True
  74. End Sub
  75. Function IsWbOpen(wbName As String) As Boolean
  76. On Error Resume Next
  77. IsWbOpen = Len(Workbooks(wbName).Name)
  78. End Function
Advertisement
Add Comment
Please, Sign In to add comment