Code that will put the file name in the last column for multiple workbooks

dstar

New Member
Joined
Oct 20, 2016
Messages
7
Big props to whoever knows how to do this. I have are around 100 different workbooks that I want to add a column at the end to that adds the file name to each row. Instead of going into each workbook and manually adding the file name to the last column does anyone know a code that can do this automatically? I've spent way too much time trying to figure this out.

Thank you!!!
 

Excel Facts

Quick Sum
Select a range of cells. The total appears in bottom right of Excel screen. Right-click total to add Max, Min, Count, Average.
If all of the workbooks are in a single directory and the workbook hosting the code is in the same directory then try this. It is assumed that only sheet 1 of each workbook applies.
Code:
Sub addFileName()
Dim wb As Workbook, lc As Long, fPath As String, fName As String
fPath = ThisWorkbook.Path
If Right(fPath, 1) <> "\" Then fPath = fPath & "\"
fName = Dir(fPath & "*.xl*")
    Do While fName <> ""
        If fName = ThisWorkbook.Name Then GoTo SKIP:
            Set wb = Workbooks.Open(fPath & fName)
            lc = wb.Sheets(1).Cells.Find("*", , xlFormulas, xlPart, xlByColumns, xlPrevious).Column
            wb.Sheets(1).Cells(2, lc + 1).Resize(wb.Sheets(1).UsedRange.Rows.Count - 1, 1) = wb.Name
            Application.DisplayAlerts = False
                wb.Close True, fPath & fName
            Application.DisplayAlerts = True
SKIP:
            fName = Dir
    Loop
End Sub
 
Upvote 0

Forum statistics

Threads
1,223,060
Messages
6,169,860
Members
452,286
Latest member
noclue2000

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