How can I rename sheets when combining Workbooks? - excel

I need to combine workbooks from a folder, and I found the below code which should do exactly what I need. The code is from here.
The issue I am encountering, that the worksheets in my workbooks all have the same long title, and it seems to crash the Sub as excel can't auto rename the sheets due to conflict (e.g. there is no room to append with (2) and (3) etc.).
How can I add onto the code to rename the sheets something arbitrary, e.g. Copied1, Copied 2, etc... ?
Sub MergeWorkbooks()
Dim FolderName As String
Dim directory As String, fileName As String
Dim wb1 As Workbook, wb2 As Workbook
Dim ws As Worksheet
Set wb1 = Workbooks.Add
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Please select a folder."
.AllowMultiSelect = False
.Show
On Error Resume Next
FolderName = .SelectedItems(1)
Err.Clear
On Error GoTo 0
End With
directory = FolderName & "\"
fileName = Dir(directory & "*.xls?")
Do While fileName <> ""
Set wb2 = Workbooks.Open(directory & fileName)
For Each ws In wb2.Sheets
ws.Copy after:=wb1.Sheets(Sheets.Count)
Next ws
wb2.Close savechanges:=False
fileName = Dir
Loop
End Sub

Use variable i to rename your sheets before moving them to your other book. The i corresponds to the book the sheet came from in your loop.
So the 5th book will have a sheet name of Sheet1 5 and the 6th book will be Sheet1 6 and so on for every sheet in every book.
Dim i As Long
i = 1
Do While Filename <> ""
Set wb2 = Workbooks.Open(directory & Filename)
For Each ws In wb2.Sheets
ws.Name = ws.Name & Chr(32) & i '<-- Rename
ws.Copy after:=wb1.Sheets(Sheets.Count)
Next ws
wb2.Close savechanges:=False
Filename = Dir
i = i + 1 '<-- Increment i for next bok
Loop
This will only work if the code is ran once - If you try to re-run the code on the same books with similar names, the index i will have already been used. If this is a problem, you can rename the sheets to corrospond with the number of sheets that are on the book (wb1.Sheets.Count)

Building off of urdearboy's response, I added user prompts to choose whether a batch rename is wanted, and if it is, to choose the batch name. It's nice to have the option when needed!
Sub MergeWorkbooks()
Dim FolderName As String
Dim directory As String, fileName As String
Dim wb1 As Workbook, wb2 As Workbook
Dim ws As Worksheet
Dim iAnswer As VbMsgBoxResult
Dim xAppend As String
Set wb1 = Workbooks.Add
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Please select a folder."
.AllowMultiSelect = False
.Show
On Error Resume Next
FolderName = .SelectedItems(1)
Err.Clear
On Error GoTo 0
End With
directory = FolderName & "\"
fileName = Dir(directory & "*.xls?")
'Prompt user to decide if batch rename is required
iAnswer = MsgBox("Would you like to batch rename the worksheets?", vbYesNoCancel + vbQuestion + vbDefaultButton1, "Sort Worksheets")
'vbYes: Rename Worksheets
If iAnswer = vbYes Then
1:
xAppend = InputBox(Prompt:= _
"Enter new batch name for worksheets." _
& vbNewLine & vbNewLine & _
"Sheets will be appended with number based on the order in which they are copied." _
& vbNewLine & vbNewLine & _
"If 'Cancel' is selected, worksheets will be renamed as number only, based on order in which they are copied.", _
Title:="Naming Convention")
If InStr(xAppend, "<") > 0 _
Or InStr(xAppend, ">") > 0 _
Or InStr(xAppend, ":") > 0 _
Or InStr(xAppend, Chr(34)) > 0 _
Or InStr(xAppend, "/") > 0 _
Or InStr(xAppend, "\") > 0 _
Or InStr(xAppend, "|") > 0 _
Or InStr(xAppend, "?") > 0 _
Or InStr(xAppend, "*") > 0 _
Then
MsgBox "Suggested filename contains an invalid character"
GoTo 1
End If
Dim i As Long
i = 1
Do While fileName <> ""
Set wb2 = Workbooks.Open(directory & fileName)
For Each ws In wb2.Sheets
ws.Name = xAppend & i '<-- Rename
ws.Copy after:=wb1.Sheets(Sheets.Count)
Next ws
wb2.Close savechanges:=False
fileName = Dir
i = i + 1 '<-- Increment i for next bok
Loop
'vbNo: Rename Worksheets
ElseIf iAnswer = vbNo Then
Do While fileName <> ""
Set wb2 = Workbooks.Open(directory & fileName)
For Each ws In wb2.Sheets
ws.Copy after:=wb1.Sheets(Sheets.Count)
Next ws
wb2.Close savechanges:=False
fileName = Dir
Loop
'vb Canel: Exit
Else
Exit Sub
End If
End Sub

Related

Trying to get my VBA script to export specific sheets to csv from an array but continue to get Run Time 1004 on the thirdsheet

I have been working on my code to get the system to export specific sheet based only on what is visible in the system yet, for some reason I continue to struggle when it is trying to run the export with getting only the specified sheets to export. I know this has to be something simple that I am missing but I am unable to locate what that might be. Any assistance would be greatly appreciated.
Private Sub ExportSheets() 'saves all visible sheets as new xlsx files
Dim ws As Worksheet, wbNew As Workbook
Dim myWorksheets() As String 'Array to hold worksheet names to copy
Dim sFolderPath As String
Dim fs As Object
Dim FileName1 As String
Dim i As Integer
Set wbNew = Application.ThisWorkbook
FileName1 = Range("PMC_Name").Value
sFolderPath = wbNew.Path & "\" & FileName1 & " - Import Templates"
myWorksheets = Split("Chart of Accounts, Custom Mapping File, Custom Chart of Accounts,Conventional Default COA,Conventional Mapping File,CONV Chart of Accounts,HUD Chart of Accounts,Affordable Default COA,Affordable Mapping File,Entities,Properties,Floors,Units,Area Measurement,Tenants,Account Labels,Leases,Scheduled Charges,Tenant Beginning Balances,Vendors,Vendor Beginning Balances,Customers,Customer Beginning Balances,GL Beginning Balances,GL Detail,Bank Accounts,Budgets,Budgeting COA,Budgeting Conventional COA,Budgeting Affordable COA,Budgeting Job Positions,Budgeting Employee List,Budgeting Workers Comp,Expense Pools,Lease Recoveries,Index Code,Lease Sales,Option Types,Clause Types,Lease Clauses,Lease Options,Budgeting Current Budget Import,Job Cost,Draw Model Detail,Job Cost History,Job Cost Budgets,Fixed Assets,Condo Properties,Owners,Ownership Information,Ownership Billing,Owner Charges", ",") 'this contains an array of the sheets. You need to put the real sheet names here.
If Dir(sFolderPath, vbDirectory) <> "" Then
'If the folder does exist error
MsgBox "The folder currently exists, please rename or delete the folder.", vbCritical, "Error"
Exit Sub
'If the folder does not exist create folder and export
End If
MkDir sFolderPath
Application.ScreenUpdating = False
For Each ws In ThisWorkbook.Sheets 'for each worksheet
'if it's visible:
If Sheets(myWorksheets(i)).visible Then
Debug.Print "Exporting: " & ws.Name
ws.Copy '(if no params specified, COPY creates + activates a new wb)
Set wbNew = Application.ActiveWorkbook 'get new wb object
wbNew.SaveAs sFolderPath & "\" & ws.Name & ".csv", 23 'save new wb
wbNew.Close 'close new wb
Set wbNew = Nothing 'cleanup
End If
Next ws
Set ws = Nothing 'clean up
Application.ScreenUpdating = False
MsgBox "Sheet Export is now Complete. You can find the files at the following path." & vbNewLine & vbNewLine & sFolderPath, vbExclamation, "Export Sheets Complete"
End Sub
Export Sheets
Sub ExportSheets() 'saves all visible sheets as new xlsx files
Const PROC_TITLE As String = "Export Sheets"
Const SHEET_LIST As String _
= "Chart of Accounts,Custom Mapping File,Custom Chart of Accounts," _
& "Conventional Default COA,Conventional Mapping File," _
& "CONV Chart of Accounts,HUD Chart of Accounts," _
& "Affordable Default COA,Affordable Mapping File,Entities," _
& "Properties,Floors,Units,Area Measurement,Tenants,Account Labels," _
& "Leases,Scheduled Charges,Tenant Beginning Balances,Vendors," _
& "Vendor Beginning Balances,Customers,Customer Beginning Balances," _
& "GL Beginning Balances,GL Detail,Bank Accounts,Budgets," _
& "Budgeting COA,Budgeting Conventional COA,Budgeting Affordable COA," _
& "Budgeting Job Positions,Budgeting Employee List," _
& "Budgeting Workers Comp,Expense Pools,Lease Recoveries,Index Code," _
& "Lease Sales,Option Types,Clause Types,Lease Clauses,Lease Options," _
& "Budgeting Current Budget Import,Job Cost,Draw Model Detail," _
& "Job Cost History,Job Cost Budgets,Fixed Assets,Condo Properties," _
& "Owners,Ownership Information,Ownership Billing,Owner Charges"
Dim swb As Workbook: Set swb = ThisWorkbook
Dim sws As Worksheet: Set sws = swb.Sheets("Sheet1") ' adjust!
Dim PMC As String: PMC = CStr(sws.Range("PMC_Name").Value)
Dim dFolderPath As String
dFolderPath = swb.Path & "\" & PMC & " - Import Templates\"
If Len(Dir(dFolderPath, vbDirectory)) > 0 Then
MsgBox "The folder already exists. " _
& "Please rename or delete the folder.", vbCritical, PROC_TITLE
Exit Sub
End If
MkDir dFolderPath
Dim SheetNames() As String: SheetNames = Split(SHEET_LIST, ",")
Application.ScreenUpdating = False
Dim dwb As Workbook, ssh As Object, SheetName
For Each SheetName In SheetNames
On Error Resume Next
Set ssh = swb.Sheets(SheetName)
On Error GoTo 0
If Not ssh Is Nothing Then ' sheet exists
If ssh.Visible Then ' sheet is visible
Debug.Print "Exporting: " & ssh.Name
ssh.Copy ' creates a single-sheet workbook
Set dwb = Workbooks(Workbooks.Count)
dwb.SaveAs dFolderPath & ssh.Name & ".csv", xlCSVWindows ' 23
dwb.Close SaveChanges:=False
'Else ' sheet is not visible; do nothing
End If
Set ssh = Nothing ' reset for the next iteration
'Else ' sheet doesn't exist; do nothing
End If
Next SheetName
Application.ScreenUpdating = True
MsgBox "Sheet Export is now complete. " _
& "You can find the files in the following path:" & vbLf & vbLf _
& dFolderPath, vbInformation, PROC_TITLE
End Sub

Copy data from a workbook to an existing workbook

I'm working on Excel for Mac, v16.53, with OS Catalina v10.15.7
I have an Excel workbook called SCRIPT with two sheets.
Sheet 1 has data entry areas and sheet 2 compiles those entries into a pseudo-table. The data in sheet 1 changes with every new person that is interviewed.
The data in sheet 2 is in columns A, B, H, I and J. It is non-contiguous and doesn't always have row 1 populated.
I can copy those five columns to a new csv file called Telesales-Leads-TODAY'S DATE.
The issue is when there already is a Telesales-Leads-TODAY'S DATE file.
The script is supposed to:
If Telesales-Leads-TODAY'S DATE file does not exist:
Start a new one.
Copy/paste the new SCRIPT data and save the Telesales-Leads-TODAY'S DATE file.
If a Telesales-Leads-TODAY'S DATE file does exist:
Copy the new data from the SCRIPT workbook to the first 100% empty column of the Telesales-Leads-TODAY'S DATE file.
Save the file with the same name (Telesales-Leads-TODAY'S DATE) in csv format.
It throws an error AFTER it copies the data from the SCRIPT workbook but BEFORE it has a chance to completely open the Telesales-Leads-TODAY'S DATE file.
I am using the MsgBox to debug.
Sub BackUpScriptData()
Dim strFileName As String
Dim strFileExists As String
Dim finalcolumn As Integer
Dim firstemptycolumn As Integer
Dim csvOpened As Workbook
Dim oneCell As Range
Dim myCSVFileName As String
Dim myWB As Workbook
Dim tempWB As Workbook
Dim rngToSave As Range
Dim col As String
Dim ColumnNumber As Integer
Dim ColumnLetter As String
Dim colstart As String
Dim CellAddress As String
Dim TestChar As String
Dim NumberToLetter As String
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.DisplayAlerts = False
On Error GoTo err
strFileName = "/Users/XXXXXXXX/Library/Group Containers/XXXXXXXX.Office/User Content.localized/Startup.localized/Excel/" & "Telesales-Leads-" & VBA.Format(VBA.Now, "mm-dd-yyyy") & ".csv"
strFileExists = Dir(strFileName)
If strFileExists = "" Then
MsgBox strFileName & " ~~~~~~~~doesn't exist"
Set myWB = ThisWorkbook
myCSVFileName = "/Users/XXXXXXXX/Library/Group Containers/XXXXXXXX.Office/User Content.localized/Startup.localized/Excel/" & "Telesales-Leads-" & VBA.Format(VBA.Now, "mm-dd-yyyy") & ".csv"
Set rngToSave = Range("A1:B69,H1:J69")
rngToSave.Copy
Set tempWB = Application.Workbooks.Add(1)
With tempWB
.Sheets(1).Range("A1").PasteSpecial xlPasteValues
.SaveAs FileName:=myCSVFileName, FileFormat:=xlCSV, CreateBackup:=False
.Close
End With
Else
Set myWB = ThisWorkbook
Set rngToSave = Range("A1:B69,H1:J69")
rngToSave.Copy
Set csvOpened = Workbooks.Open(FileName:=strFileName)
MsgBox "csvOpened is " & csvOpened
With csvOpened
Set oneCell = Range("A1")
Do While WorksheetFunction.CountA(oneCell.EntireColumn)
Set oneCell = oneCell.Offset(0, 1)
Loop
MsgBox "oneCell.Column is " & oneCell.Column
End With
CellAddress = Cells(1, ColNum).Address
For i = 2 To Len(CellAddress)
TestChar = Mid(CellAddress, i, 1)
If TestChar = "$" Then Exit For
NumberToLetter = NumberToLetter & Mid(CellAddress, i, 1)
Next i
MsgBox "colstart is " & colstart
With csvOpened
.Sheets(1).Range(colstart & "1").PasteSpecial xlPasteValues
.SaveAs FileName:=myCSVFileName, FileFormat:=xlCSV, CreateBackup:=False
.Close
End With
End If
err: MsgBox "failed to copy."
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub
The code is essentially the same for creating a new workbook or updating an existing, the only difference being the column where the data is to be pasted. As this is a csv file then UsedRange is a simple way to determine the last clear column.
Sub BackUpScriptData2()
Const FOLDER = "/Users/XXXXXXXX/Library/Group Containers/XXXXXXXX.Office/" & _
"User Content.localized/Startup.localized/Excel/"
Const PREFIX = "Telesales-Leads-"
Dim wb As Workbook, wbCSV As Workbook
Dim ws As Worksheet, rngToSave As Range
Dim colNum As Long, myCSVFileName As String
myCSVFileName = PREFIX & VBA.Format(VBA.Now, "mm-dd-yyyy") & ".csv"
' check if file exists
If Len(Dir(FOLDER & myCSVFileName)) = 0 Then
' not exists
MsgBox "'" & myCSVFileName & "'" & vbCrLf & _
"does not exist, it will be created", vbInformation, FOLDER
Set wbCSV = Workbooks.Add()
colNum = 1
Else
' exists
Set wbCSV = Workbooks.Open(FOLDER & myCSVFileName)
With wbCSV.Sheets(1).UsedRange
colNum = .Column + .Columns.Count
End With
MsgBox "'" & myCSVFileName & "'" & vbCrLf & _
"exists, it will extended from column " & colNum, vbInformation, FOLDER
End If
' copy and save
Set wb = ThisWorkbook
Set ws = wb.Sheets("Sheet2")
Set rngToSave = ws.Range("A1:B69,H1:J69")
rngToSave.Copy
With wbCSV
.Sheets(1).Cells(1, colNum).PasteSpecial xlPasteValues
.SaveAs Filename:=FOLDER & myCSVFileName, FileFormat:=xlCSV, CreateBackup:=False
.Close False
End With
MsgBox "File saved to " & myCSVFileName, vbInformation, FOLDER
End Sub

VBA Loop directory removing (by sheet name) all sheets but one from each workbook

I have previously posted on here about using VBA to loop through a folder and remove known passwords from each workbook therein. Thought I could use the same code and just insert code the removes all sheets except one (by reference to sheet name), but no such luck.
Any VBA pros out there that can help?
Sub loop_sheets_del()
Dim MyFile as String, str As String, MyDir = "[directory]"
MyFile = Dir(MyDir & "*.xlsx")
ChDir MyDir
Application.ScreenUpdating = 0
Application.DisplayAlerts = 0
Do While Myfile <> ""
Workbooks.Open (MyFile)
If ws.Name <> "name of sheet to keep" Then
ws.Delete
End If
Next ws (error indicates problem is here)
ActiveWorkbook.Close True
End With
MyFile = Dir()
Loop
End Sub
Delete Sheets
In the current setup, the following will delete all sheets except the one named Master in all files with the xls* extension (e.g. xls, xlsx, xlsm: do not use wild characters in the code; it is covered by Instr) in the specified folder F:\Test\2020\64504925 and all of its subfolders.
The Code
Option Explicit
' Run only this sub after you have adjusted the path, the worksheet name
' and the file extension.
Sub loopSubFolders()
Application.ScreenUpdating = False
loopSubFoldersInitialize "F:\Test\2020\64504925", "Master", "xls"
Application.ScreenUpdating = True
MsgBox "Sheets deleted.", vbInformation, "Success"
End Sub
Sub loopSubFoldersInitialize(ByVal FolderPath As String, _
ByVal SheetName As String, _
Optional ByVal FileExtension As String = "")
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
loopSubFoldersRecursion fso, fso.GetFolder(FolderPath), SheetName, _
FileExtension
End Sub
Sub loopSubFoldersRecursion(fso As Object, _
fsoFolder As Object, _
ByVal SheetName As String, _
Optional ByVal FileExtension As String = "")
Dim fsoSubFolder As Object
Dim fsofile As Object
For Each fsoSubFolder In fsoFolder.SubFolders
loopSubFoldersRecursion fso, fsoSubFolder, SheetName, FileExtension
Next
If FileExtension = "" Then
For Each fsofile In fsoFolder.Files
'Debug.Print fsofile.Path
Next
Else
For Each fsofile In fsoFolder.Files
If InStr(1, fso.GetExtensionName(fsofile.Path), _
FileExtension, vbTextCompare) > 0 Then
Dim wb As Workbook
Set wb = Workbooks.Open(fsofile.Path)
deleteSheetsExceptOneByName wb, SheetName
Debug.Print fsofile.Path
wb.Close SaveChanges:=True
End If
Next fsofile
End If
End Sub
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose: Deletes all sheets in a workbook except the one specified
' by its name.
' Remarks: The code uses the dictionary to hold all the sheet names.
' Only if the specified sheet exists, it will be removed from
' the dictionary and the remaining sheets in it will be deleted
' in one go. Otherwise no action will be taken.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function deleteSheetsExceptOneByName(Book As Workbook, _
ByVal SheetName As String) _
As Long
' Initialize error handling.
Const ProcName As String = "deleteSheetsExceptOneByName"
On Error GoTo clearError ' Turn on error trapping.
' Validate workbook.
If Book Is Nothing Then
GoTo NoWorkbook
End If
' Define dictionary.
With CreateObject("Scripting.Dictionary")
.CompareMode = vbTextCompare
' Write sheet names to dictionary.
Dim sh As Object
For Each sh In Book.Sheets
.Add sh.Name, Empty
Next sh
' Validate sheet name string.
If Not .Exists(SheetName) Then
GoTo NoSheet
End If
' Remove sheet name string from the dictionary.
.Remove (SheetName)
' Validate number of sheets.
If .Count = 0 Then
GoTo OneSheet
End If
' Delete sheets.
Application.DisplayAlerts = False
Book.Sheets(.Keys).Delete
Application.DisplayAlerts = True
deleteSheetsExceptOneByName = .Count
GoTo SheetsDeleted
End With
NoWorkbook:
Debug.Print "'" & ProcName & "': No workbook ('Nothing')."
GoTo ProcExit
NoSheet:
Debug.Print "'" & ProcName & "': No sheet named '" & SheetName _
& "' in workbook."
GoTo ProcExit
OneSheet:
Debug.Print "'" & ProcName & "': Sheet '" & Book.Sheets(SheetName).Name _
& "' is the only sheet in workbook."
GoTo ProcExit
SheetsDeleted:
If deleteSheetsExceptOneByName > 1 Then
Debug.Print "'" & ProcName & "': Deleted " _
& deleteSheetsExceptOneByName & " sheets in workbook."
Else
Debug.Print "'" & ProcName & "': Deleted 1 sheet in workbook."
End If
GoTo ProcExit
clearError:
Debug.Print "'" & ProcName & "': " & vbLf _
& " " & "Run-time error '" & Err.Number & "':" & vbLf _
& " " & Err.Description
On Error GoTo 0 ' Turn off error trapping.
GoTo ProcExit
ProcExit:
End Function
You're missing the first part of the requisite For Each loop.
Also best to use a Workbook variable to refer to each workbook being opened and modified:
Do While Myfile <> ""
Dim MyWB As Workbook
Set MyWB = Workbooks.Open(MyFile)
For Each ws in MyWB.Worksheets
If ws.Name <> "name of sheet to keep" Then
ws.Delete
End If
Next
myWB.Close True
MyFile = Dir
Loop
Just for the sake of completeness I added the code and checked if the sheet to be kept exists so in case it doesn't, there isn't an error raised.
Read the code's comments.
Public Sub DeleteSheetsExceptInFiles()
Dim targetFile As String
Dim targetDirectory As String
Dim keepSheetName As String
Dim str As String
' Basic error handling
On Error GoTo CleanFail
' Define directory, file and sheet name
targetDirectory = "C:\Temp\"
targetFile = Dir(targetDirectory & "*.xlsx")
keepSheetName = "name of sheet to keep"
' Speed up process
Application.ScreenUpdating = False
Application.DisplayAlerts = False
' Loop through files
Do While targetFile <> ""
Dim targetWorkbook As Workbook
Set targetWorkbook = Workbooks.Open(targetDirectory & targetFile)
' Check if sheet to keep exists
Dim targetSheet As Worksheet
Dim keepSheetExists As Boolean
On Error Resume Next
keepSheetExists = targetWorkbook.Worksheets(keepSheetName)
On Error GoTo CleanFail
' Proceed if sheet exists
If keepSheetExists = True Then
For Each targetSheet In targetWorkbook.Worksheets
' Delete all sheets except the one to keep
If targetSheet.Name <> keepSheetName Then
targetSheet.Delete
End If
Next targetSheet
End If
targetWorkbook.Close True
targetFile = Dir()
Loop
CleanExit:
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Exit Sub
CleanFail:
Debug.Print "Something went wrong: " & Err.Description
Resume CleanExit
End Sub

I am copying multiple excel files into a single workbook an want cell A1 data to be listed on all lines copied from that workbook

Sub Merger()
Dim wb As Workbook, sh As Worksheet, fPath As String, fName As String
Set sh = ThisWorkbook.Sheets(1)
fPath = ThisWorkbook.Path 'If files are in a different directory than master, replace path here
If Right(fPath, 1) <> "\" Then fPath = fPath & "\" 'Make sure separator is on end of path
fName = Dir(fPath & "*.xl*") 'get all Excel files in directory
Do
If fName <> ThisWorkbook.Name Then
Set wb = Workbooks.Open(fPath & fName)
With wb.Sheets(1)
If Application.CountA(.Rows(2)) > 0 Then
.UsedRange.Offset().Copy sh.Cells(Rows.Count, 1).End(xlUp)(2)
End If
End With
wb.Close False
End If
fName = Dir
Loop While fName <> ""
ActiveCell.Offset(-34, -7).Range("A1:T1").Select
ActiveCell.FormulaR1C1 = _
"hb_golden_1154317527.txt)"
ActiveCell.Offset(29, 0).Range("A1").Select
End Sub
Like I said I would to insert A1 into each Consecutive line of data not sure where to start.
sample file for excel merged

Rename all worksheet names as workbook names in a folder

Seeking support to edit below codes in such a way that it renames all worksheets (excel) similar to their workbooknames within a folder (loop). If workbook has more than one sheet then rename it as workbookname(1),workbookname(2) etc.
Sub EditSheetName()
Dim NewName
NewName = Replace(ActiveWorkbook. Name, ".xl*", "")
ActiveSheet.Select
ActiveSheet.Name = NewName
End Sub
Maybe just a simple loop:
I haven't figured out how to replace the ".xlsx" using a wildcard, I would assume it would be either ".xlsm" or ".xlsx", you can change them in the code
Sub LoopThroughFolder()
Dim MyFile As String, Str As String, MyDir As String, Wb As Workbook
Dim sh As Worksheet
Dim s As String, n As String
Set Wb = ThisWorkbook
'change the address to suite
MyDir = "C:\Users\dmorrison\Downloads\TestFolderLoop\"
MyFile = Dir(MyDir & "*.xls*") 'change file extension
ChDir MyDir
Application.ScreenUpdating = 0
Application.DisplayAlerts = 0
Do While MyFile <> ""
Workbooks.Open (MyFile)
s = ActiveWorkbook.Name
n = Replace(s, ".xls", "") 'change the file extension
i = 1
For Each sh In Sheets
sh.Name = n & "(" & i & ")"
i = i + 1
Next sh
ActiveWorkbook.Close True
MyFile = Dir()
Loop
End Sub
For multiple sheets, you will want an if statement:
Dim s As String, i as Integer
If Sheets.Count=1 Then
s = Replace(ActiveWorkbook.Name,".xlsx","")
ActiveSheet.Name = s
Else
For i = 1 to Sheets.Count
s = Replace(ActiveWorkbook.Name,".xlsx","")
Sheets(i).Name = s & "(" & i & ")"
Next i
End If
I have it this way so the (#) only shows up for multiple. You would only need the loop in the Else section if you don't care.

Resources