VBA Merge specific sheets from files in a folder

jskasango

Board Regular
Joined
Jul 18, 2012
Messages
202
Office Version
  1. 365
Platform
  1. Windows
VBA Merge specific sheets from files in a folder. I want my sheets to be merged into ONE sheet after matching the column headers. If its ok with you, column A can contain the source file name. Thanks in advance.
 
What means second time running. It only need one time running to add all files at selected folder to active sheet?
What means active area?
Also you don't answer exactly how we take header? Then I take all headers from first files and then each one doesn't exist at first file add after last column.
 
Upvote 0

Excel Facts

Which lookup functions find a value equal or greater than the lookup value?
MATCH uses -1 to find larger value (lookup table must be sorted ZA). XLOOKUP uses 1 to find values greater and does not need to be sorted.
Thank you very much [B]maabadi[/B] for the code. I need to merge data from various years and in many different series. Meaning I will run the code multiple times to make the merged data sets stored in many different folders. I have just realized that my excel is misbehaving, so once it stabilizes, then I will use the code.
 
Upvote 0
You're Welcome & Thanks for feedback. For second time running & others data added after last row of data based column headers. If one if headers doesn't exist add after last column also.
 
Upvote 0
It worked on first run! When I run it a second time it only picks the headers and places the source filename in column A, the data in the active area is ignored! But the first run, it worked fine.
After a few tweaks here and there, I am happy, very happy with your solution. It now looks like this:-
Please look at line 82 and help me make it save the CSV by picking the current fodername like this (FoldernameMASTERSTACK.CSV).
I have put in bold the parts that I changed.
==========================================================================
  1. 'Code courtesy of maabadi, of Mrexcel.com forum
  2. Sub ImportFiles3()
  3. Dim xWS As Worksheet, xTWB As Workbook, DestSheet As Worksheet, Head As Range
  4. Dim xStrAWBName As String, FolderName As String, sItem As String, Header As Long
  5. Dim FolderPath As String, fldr As FileDialog, Lr As Long, LCD As Long, R As Long
  6. Dim os As Long, LrS As Long, LCS As Long, FileName As String
  7. On Error Resume Next
  8. Set xTWB = ThisWorkbook
  9. Worksheets.Add
  10. Set DestSheet = xTWB.ActiveSheet

  11. Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
  12. With fldr
  13. .Title = "Select a Folder containing files to merge"
  14. .AllowMultiSelect = False
  15. '.InitialFileName = Application.DefaultFilePath
  16. If .Show <> -1 Then GoTo NextCode
  17. sItem = .SelectedItems(1)
  18. End With
  19. NextCode:

  20. FolderName = sItem
  21. Set fldr = Nothing
  22. FolderPath = FolderName & "\"
  23. FileName = Dir(FolderPath & "*.xls*")
  24. Application.ScreenUpdating = False
  25. Application.Calculation = xlCalculationManual
  26. Application.DisplayAlerts = False
  27. Do While FileName <> ""
  28. Workbooks.Open FileName:=FolderPath & FileName, ReadOnly:=True
  29. xStrAWBName = ActiveWorkbook.Name
  30. For Each xWS In ActiveWorkbook.Sheets
  31. If xWS.Name = "Master" Then
  32. Lr = DestSheet.Range("A" & Rows.Count).End(xlUp).Row
  33. LrS = xWS.Range("A" & Rows.Count).End(xlUp).Row
  34. LCS = xWS.Cells(1, Columns.Count).End(xlToLeft).Column + 1
  35. LCD = DestSheet.Cells(1, Columns.Count).End(xlToLeft).Column + 1
  36. If Lr = 1 Then
  37. Range(DestSheet.Cells(0, 2), DestSheet.Cells(2, LCS)).Value = Range(xWS.Cells(1, 1), xWS.Cells(2, LCS - 1)).Value
  38. DestSheet.Range("A1").Value = "FileName"
  39. End If
  40. Set Head = xWS.Range("A1")
  41. For os = 0 To xWS.Cells(2, Columns.Count).End(xlToLeft).Column - 1
  42. On Error Resume Next
  43. Header = 0
  44. Header = WorksheetFunction.Match(Head.Offset(0, os), DestSheet.Rows(1), 0)
  45. On Error GoTo 0
  46. If Header = 0 Then
  47. DestSheet.Cells(1, LCD) = Head.Offset(0, os)
  48. Header = LCD
  49. LCD = LCD + 1
  50. End If
  51. If Lr = 1 Then
  52. Range(DestSheet.Cells(Lr + 2, Header), DestSheet.Cells(Lr + LrS - 1, Header)).Value = Range(xWS.Cells(3, os + 1), xWS.Cells(LrS, os + 1)).Value
  53. Else
  54. Range(DestSheet.Cells(Lr + 1, Header), DestSheet.Cells(Lr + LrS - 2, Header)).Value = Range(xWS.Cells(3, os + 1), xWS.Cells(LrS, os + 1)).Value
  55. End If
  56. Next os
  57. If Lr = 1 Then
  58. Range(DestSheet.Cells(Lr + 2, 1), DestSheet.Cells(Lr + LrS - 1, 1)).Value = Left(FileName, Application.WorksheetFunction.Find(".", FileName) - 1)
  59. Else
  60. Range(DestSheet.Cells(Lr + 1, 1), DestSheet.Cells(Lr + LrS - 2, 1)).Value = Left(FileName, Application.WorksheetFunction.Find(".", FileName) - 1)
  61. End If
  62. End If
  63. Next xWS
  64. Workbooks(xStrAWBName).Close
  65. FileName = Dir()
  66. Loop

  67. DestSheet.Activate
  68. DestSheet.Name = "xStrAWBName"
  69. Rows("2:2").Select
  70. Selection.AutoFilter
  71. ActiveWindow.FreezePanes = True
  72. Columns("A:EA").EntireColumn.AutoFit

  73. xTWB.Save
  74. Sheets("xStrAWBName").Select
  75. Sheets("xStrAWBName").Move
  76. ActiveWorkbook.SaveAs FileName:=Application.GetSaveAsFilename(""), FileFormat:=xlCSV, CreateBackup:=False
  77. Application.ScreenUpdating = True
  78. Application.DisplayAlerts = True
  79. Application.Calculation = xlCalculationAutomatic
  80. MsgBox "MASTERS MERGED for " & xStrAWBName & vbLf & vbLf _
  81. & "YOU CAN NOW FILTER AND KNOCK OUT SETS WITH NO PLANTING DATES!", vbInformation
  82. End Sub
 
Upvote 0
I changed code to this but don't test it?

I add these
1. TO Dim Part
, DD As Long, FN2 As String
2. After Foldername
DD = InStrRev(FolderName, "\")
FN2 = Right(FolderName, Len(FolderName) - DD)

3. AND change Filename at Lin82
VBA Code:
Sub ImportFiles3()
Dim xWS As Worksheet, xTWB As Workbook, DestSheet As Worksheet, Head As Range
Dim xStrAWBName As String, FolderName As String, sItem As String, Header As Long
Dim FolderPath As String, fldr As FileDialog, Lr As Long, LCD As Long, R As Long
Dim os As Long, LrS As Long, LCS As Long, FileName As String, DD As Long, FN2 As String
On Error Resume Next
Set xTWB = ThisWorkbook
Worksheets.Add
Set DestSheet = xTWB.ActiveSheet


Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder containing files to merge"
.AllowMultiSelect = False
'.InitialFileName = Application.DefaultFilePath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With


NextCode:


FolderName = sItem
DD = InStrRev(FolderName, "\")
FN2 = Right(FolderName, Len(FolderName) - DD)
Set fldr = Nothing
FolderPath = FolderName & "\"
FileName = Dir(FolderPath & "*.xls*")
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.DisplayAlerts = False
Do While FileName <> ""
Workbooks.Open FileName:=FolderPath & FileName, ReadOnly:=True
xStrAWBName = ActiveWorkbook.Name
For Each xWS In ActiveWorkbook.Sheets
If xWS.Name = "Master" Then
Lr = DestSheet.Range("A" & Rows.Count).End(xlUp).Row
LrS = xWS.Range("A" & Rows.Count).End(xlUp).Row
LCS = xWS.Cells(1, Columns.Count).End(xlToLeft).Column + 1
LCD = DestSheet.Cells(1, Columns.Count).End(xlToLeft).Column + 1
If Lr = 1 Then
Range(DestSheet.Cells([B]0[/B], 2), DestSheet.Cells(2, LCS)).Value = Range(xWS.Cells(1, 1), xWS.Cells(2, LCS - 1)).Value
DestSheet.Range("A1").Value = "FileName"
End If
Set Head = xWS.Range("A1")
For os = 0 To xWS.Cells(2, Columns.Count).End(xlToLeft).Column - 1
On Error Resume Next
Header = 0
Header = WorksheetFunction.Match(Head.Offset(0, os), DestSheet.Rows(1), 0)
On Error GoTo 0


If Header = 0 Then
DestSheet.Cells(1, LCD) = Head.Offset(0, os)
Header = LCD
LCD = LCD + 1
End If
If Lr = 1 Then
Range(DestSheet.Cells(Lr + 2, Header), DestSheet.Cells(Lr + LrS - 1, Header)).Value = Range(xWS.Cells(3, os + 1), xWS.Cells(LrS, os + 1)).Value
Else
Range(DestSheet.Cells(Lr + 1, Header), DestSheet.Cells(Lr + LrS - 2, Header)).Value = Range(xWS.Cells(3, os + 1), xWS.Cells(LrS, os + 1)).Value
End If
Next os
If Lr = 1 Then
Range(DestSheet.Cells(Lr + 2, 1), DestSheet.Cells(Lr + LrS - 1, 1)).Value = Left(FileName, Application.WorksheetFunction.Find(".", FileName) - 1)
Else
Range(DestSheet.Cells(Lr + 1, 1), DestSheet.Cells(Lr + LrS - 2, 1)).Value = Left(FileName, Application.WorksheetFunction.Find(".", FileName) - 1)
End If
End If
Next xWS
Workbooks(xStrAWBName).Close
FileName = Dir()
Loop


DestSheet.Activate
DestSheet.Name = "xStrAWBName"
Rows("2:2").Select
Selection.AutoFilter
ActiveWindow.FreezePanes = True
Columns("A:EA").EntireColumn.AutoFit


xTWB.Save
Sheets("xStrAWBName").Select
Sheets("xStrAWBName").Move
ActiveWorkbook.SaveAs FileName:=[U]FN2 & "[/U][B][U]MASTERSTACK"[/U][/B], FileFormat:=xlCSV, CreateBackup:=False
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.Calculation = xlCalculationAutomatic
MsgBox "MASTERS MERGED for " & xStrAWBName & vbLf & vbLf _
& "YOU CAN NOW FILTER AND KNOCK OUT SETS WITH NO PLANTING DATES!", vbInformation
End Sub
 
Last edited:
Upvote 0
AND I forgot to clear bold & underline from Saveas Line change it to this:

VBA Code:
ActiveWorkbook.SaveAs FileName:=FN2 & "MASTERSTACK", FileFormat:=xlCSV, CreateBackup:=False
 
Upvote 0
One other thing. I see @sushil84p Post. It doesn't need CSV file. you can Post my first code at Post #5 I sent at this Thread with one row header and only extract sheet1.
 
Last edited:
Upvote 0
AND I forgot to clear bold & underline from Saveas Line change it to this:

VBA Code:
ActiveWorkbook.SaveAs FileName:=FN2 & "MASTERSTACK", FileFormat:=xlCSV, CreateBackup:=False
Working like MAGIC! Except that it is saving the CSV file outside the folder. It should save the CSV file in the same folder where the workbooks were fished from. WOW!
 
Upvote 0
If you want full Path then you don't need FN2 variable use FolderName
VBA Code:
ActiveWorkbook.SaveAs FileName:=FolderName & "MASTERSTACK", FileFormat:=xlCSV, CreateBackup:=False
 
Upvote 0
Sorry my Fault Try This:
VBA Code:
ActiveWorkbook.SaveAs FileName:=FolderPath & FN2 & "MASTERSTACK", FileFormat:=xlCSV, CreateBackup:=False
 
Upvote 0

Forum statistics

Threads
1,216,041
Messages
6,128,467
Members
449,455
Latest member
jesski

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top