Advertisement
Guest User

VBA

a guest
Sep 21st, 2017
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.69 KB | None | 0 0
  1. Option Explicit
  2. Sub ImportFiles()
  3. Dim MyPath As String
  4. Dim FilesInPath As String
  5. Dim MyFiles() As String
  6. Dim SourceRcount As Long
  7. Dim Fnum As Long
  8. Dim mybook As Workbook
  9. Dim basebook As Workbook
  10. Dim folderPath As String
  11. Dim strwsNmae As String
  12. folderPath = Application.ActiveWorkbook.Path
  13.  
  14. MyPath = folderPath
  15. 'Add a slash at the end if the user forget it
  16. If Right(MyPath, 1) <> "\" Then
  17. MyPath = MyPath & "\"
  18. End If
  19. 'If there are no Excel files in the folder exit the sub
  20. FilesInPath = Dir(MyPath & "*.csv")
  21. If FilesInPath = "" Then
  22. MsgBox "No files found"
  23. Exit Sub
  24. End If
  25. 'On Error GoTo CleanUp
  26. Application.ScreenUpdating = False
  27. Set basebook = ThisWorkbook
  28. 'Fill the array(myFiles)with the list of Excel files in the folder
  29. Redim Preserve MyFiles(1 To 6)
  30. For Each strwsNmae In VBA.Array("alarm_comparison*", "dtsmom_comparison*", "genmom_comparison*", "mapboard_comparison*", "scadamom_comparison*", "netmom_comparison*")
  31. Fnum = Fnum + 1
  32. MyFiles(Fnum) = NewestFile(MyPath, strwsNmae & ".csv")
  33. Next
  34. ' Fnum = 0
  35. ' Do While FilesInPath <> ""
  36. ' Fnum = Fnum + 1
  37. ' ReDim Preserve MyFiles(1 To Fnum)
  38. ' MyFiles(Fnum) = FilesInPath
  39. ' FilesInPath = Dir()
  40. ' Loop
  41. 'Loop through all files in the array(myFiles)
  42.  
  43. If Fnum > 0 Then
  44. For Fnum = LBound(MyFiles) To UBound(MyFiles)
  45. Set mybook = Workbooks.Open(MyPath & MyFiles(Fnum))
  46. mybook.Worksheets(1).Copy after:= _
  47. basebook.Sheets(basebook.Sheets.Count)
  48. On Error Resume Next
  49. ActiveSheet.Name = mybook.Name
  50. On Error Goto 0
  51.  
  52. mybook.Close savechanges:=False
  53. Next Fnum
  54. End If
  55. 'CleanUp:
  56. Application.ScreenUpdating = True
  57. End Sub
  58. Function NewestFile(Directory, FileSpec)
  59. 'John Walkenback
  60. Dim FileName As String
  61. Dim MostRecentFile As String
  62. Dim MostRecentDate As Date
  63. If Right(Directory, 1) <> "\" Then Directory = Directory & "\"
  64.  
  65. FileName = Dir(Directory & FileSpec, 0)
  66. If FileName <> "" Then
  67. MostRecentFile = FileName
  68. MostRecentDate = FileDateTime(Directory & FileName)
  69. Do While FileName <> ""
  70. If FileDateTime(Directory & FileName) > MostRecentDate Then
  71. MostRecentFile = FileName
  72. MostRecentDate = FileDateTime(Directory & FileName)
  73. End If
  74. FileName = Dir
  75. Loop
  76. End If
  77. NewestFile = MostRecentFile
  78. End Function
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement