the folowing code allows me to browse for multiple different excel files and paste them in a single sheet below each other.the excel file have the same column names but have different data in them and is working fine, my problem is i need it when it paste a file it must write the name of that file for each and every file it paste.The name of my excel file is called Familycar and the file name of other excel is called smartcar
example
eg1 CarName,Fuel,Colour
BMW,Petrol,Red
Ford,Diesel,Green
Mazda,Petrol,Grey
eg2 CarName,Fuel,Colour
Austin,Petrol,Blue
VW,Diesel,White
Audi,Petrol,Black
Result
CarName,Fuel,Colour,FileName
BMW,Petrol,Red,Familycar
Ford,Diesel,Green,Familycar
Mazda,Petrol,Grey,Familycar
Austin,Petrol,Blue,smatrtcar
VW,Diesel,White,smartcar
Audi,Petrol,Black,smartcar
Sub Button5_Click()
Dim fileStr As Variant
Dim wbk1 As Workbook, wbk2 As Workbook
Dim ws1 As Worksheet
fileStr = Application.GetOpenFilename(FileFilter:="microsoft excel files (*.xlsx), *.xlsx", Title:="Get File", MultiSelect:=True)
Set wbk1 = ActiveWorkbook
Set ws1 = wbk1.Sheets("Sheet3")
'handling first file seperately
MsgBox fileStr(1), , GetFileName(CStr(fileStr(1)))
Set wbk2 = Workbooks.Open(fileStr(1))
wbk2.Sheets(1).UsedRange.Copy ws1.Cells(ws1.Range("A" & Rows.Count).End(xlUp).Row + 2, 1)
wbk2.Close
For i = 2 To UBound(fileStr)
MsgBox fileStr(i), , GetFileName(CStr(fileStr(i)))
Set wbk2 = Workbooks.Open(fileStr(i))
wbk2.Sheets(1).UsedRange.Offset(1, 0).Copy ws1.Cells(ws1.Range("A" & Rows.Count).End(xlUp).Row + 2, 1)
wbk2.Close
Next i
Here’s your code refactored to include this requirement