I need assistance of experts in the house on how to copy source workbook names along with other data in files I am to merge in new worksheet. The code will create a new column in the new worksheet and will fill it with the source book name (preferably first column)
I have this code that merge files based on number of rows already but with no demarcation on where one ends and another begins:
Code
Sub CopyRange()
Const SHEET_PREFIX As String = "Rows "
Dim wbDest As Workbook, wbSource As Workbook
Dim wsDest As Worksheet
Dim FolderName As String, Filename As String
Dim lastSource As Long, lastDest As Long
Dim startrow As Long
Dim starttime As Double
starttime = Timer
Application.ScreenUpdating = False
Set wbDest = ThisWorkbook
Set wsDest = wbDest.Worksheets(1)
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Show
FolderName = .SelectedItems(1) & ""
End With
Filename = Dir(FolderName & Application.PathSeparator & "*.xls*")
Do While Filename <> vbNullString
If Filename <> wbDest.Name Then
Set wbSource = Workbooks.Open(FolderName & Application.PathSeparator & Filename)
With wbSource
With .Worksheets(1)
lastSource = .Cells(.Rows.Count, "A").End(xlUp).Row
If Not SheetExists(SHEET_PREFIX & lastSource - 1) Then
Set wsDest = wbDest.Worksheets.Add(after:=wbDest.Worksheets(wbDest.Worksheets.Count))
wsDest.Name = SHEET_PREFIX & lastSource - 1
startrow = 1
lastDest = 0
Else
lastSource = lastSource - 1 'don't duplicate header
Set wsDest = ThisWorkbook.Worksheets(SHEET_PREFIX & lastSource)
lastDest = wsDest.Cells(wsDest.Rows.Count, "A").End(xlUp).Row
startrow = 2
End If
.Rows(startrow).Resize(lastSource).Copy wsDest.Cells(lastDest + 1, "A")
End With
.Close False
End With
End If
Filename = Dir
Loop
MsgBox "All done in " & Format(Timer - starttime, "0.000") & " secs"
Application.ScreenUpdating = True
End Sub
Private Function SheetExists(ByVal SheetName As String) As Boolean
Dim ws As Worksheet
On Error Resume Next
Set ws = ThisWorkbook.Worksheets(SheetName)
SheetExists = Not ws Is Nothing
End Function
Display More
I have sample files for testrun too.
Thanks