This script loops through a file pathway and combines all workbooks into a master workbook and sections each workbook into a worksheet within the master file.
I have a line ws.Name = activeworksheet.Range("B1").Value
that names the sheets as a copy of the first workbook's worksheet Sheet1 and names every sheet after that like Sheet1(2).
How can this be changed to the value in cell B1 of the workbook it is consolidating into the master workbook?
rest of script:
Option Explicit
Sub CombineWorkbooks()
Dim MainWB As Workbook
Dim sDirPath As String
Dim sFileName As String
Dim sFilePath As String
Dim wb As Workbook
Dim ws As Worksheet
sDirPath = "M:\New folder"
sFileName = Dir(sDirPath & "\*.xlsx")
Set MainWB = ThisWorkbook
Do While Len(sFileName) > 0
sFilePath = sDirPath & "\" & sFileName
Set wb = Workbooks.Open(Filename:=sFilePath)
For Each ws In wb.Sheets
ws.Copy After:=MainWB.Sheets(MainWB.Sheets.Count)
ws.Name = activeworksheet.Range("B1").Value
Next ws
wb.Close SaveChanges:=False
sFileName = Dir
Loop
End Sub
activeworksheet
toActiveSheet
– DisplayNameFor Each
loop where it'sws.copy after:=mainwb.sheets
? – nick lantaB1
of that workbookwhat I want to name the worksheet as when it is moved to theMainWb
– nick lantaActiveSheet.Name = ws.Range("B1").Value
– DisplayName