Advertisement
1ff1eeff

Merge excel files

Jun 13th, 2023 (edited)
1,344
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Sub GetSheets()
  2.     Dim WriteRow As Long, _
  3.         LastCell As Range, _
  4.         WbDest As Workbook, _
  5.         WbSrc As Workbook, _
  6.         WsDest As Worksheet, _
  7.         WsSrc As Worksheet
  8.    
  9.     Set WbDest = ThisWorkbook
  10.     Set WsDest = WbDest.Sheets.Add
  11.     WsDest.Cells(1, 1) = "Шапку сюда!"
  12.    
  13.     Path = "C:\Users\User\Desktop\Пример объединения таблиц из разных файлов\"
  14.     Filename = Dir(Path & "*.xls")
  15.    
  16.     Do While Filename <> ""
  17.         Set WbSrc = Workbooks.Open(Filename:=Path & Filename, ReadOnly:=True)
  18.         Set WsSrc = WbSrc.Sheets(1)
  19.         With WsSrc
  20.             Set LastCell = .Cells.Find(What:="*", _
  21.                           After:=.Range("A1"), _
  22.                           Lookat:=xlPart, _
  23.                           LookIn:=xlFormulas, _
  24.                           SearchOrder:=xlByRows, _
  25.                           SearchDirection:=xlPrevious, _
  26.                           MatchCase:=False)
  27.             .Range(.Range("A2"), LastCell).Copy
  28.         End With
  29.         With WsDest
  30.             WriteRow = .Cells.Find(What:="*", _
  31.                           After:=.Range("A1"), _
  32.                           Lookat:=xlPart, _
  33.                           LookIn:=xlFormulas, _
  34.                           SearchOrder:=xlByRows, _
  35.                           SearchDirection:=xlPrevious, _
  36.                           MatchCase:=False).Row + 1
  37.             '.Range("A" & WriteRow).Paste
  38.            'OR
  39.            .Range("A" & WriteRow).PasteSpecial
  40.         End With
  41.         '''To clear clipboard to avoid 'large clipboard' warnings on close
  42.        Application.CutCopyMode = False
  43.    
  44.         WbSrc.Close
  45.         Filename = Dir()
  46.     Loop
  47.  
  48. End Sub
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement