Rename the only worksheet in multiple workbooks in a chosen directory - vba

I am at my wits end and have come to you for your help.
What I am trying to accomplish is to rename a single worksheet (the only worksheet), in multiple workbooks, in a chosen directory to the workbook file name in Excel.
I have found code that will work within a single workbook, however I do not know how to get it to work on multiple workbooks in a directory chosen by the user or ran from a batch/vbs file in the same directory.
Here is the code I was using on a single workbook:
Sub RenameSheet()
Dim wbname
wbname = Replace(ActiveWorkbook.Name, ".xlsx", "")
ActiveSheet.Select
ActiveSheet.Name = wbname
Range("A1").Select
End Sub
I want to be able to do this for all files in a folder chosen by the user or files in the same directory as a batch file/vbs executable file if there is a way to execute this from running either a batch or vbs file?
If there are questions or I have missing something, please let me know and I will answer to the best of my ability.
Any help will be greatly appreciated.

Open File Dialog (Pick which books to modify)
Change sheet name to wbName (your code here)
Close File (Save)
Repeat 2 - 3 for all selected books
This will need modification if there is more than 1 sheet on any of the workbooks selected. IF there is only one sheet, ActiveSheet will suffice.
Sub RenameSheet()
Dim CurrentBook As Workbook
Dim ImportFiles As FileDialog
Dim FileCount As Long 'Count of workbooks selected
Dim wbName As String
'Open File Picker
Set ImportFiles = Application.FileDialog(msoFileDialogOpen)
With ImportFiles
.AllowMultiSelect = True
.Title = "Pick Files to Adjust"
.ButtonName = ""
.Filters.Clear
.Filters.Add ".xlsx files", "*.xlsx"
.Show
End With
Application.DisplayAlerts = False
Application.ScreenUpdating = False
'Cycle through books
For FileCount = 1 To ImportFiles.SelectedItems.Count
Set CurrentBook = Workbooks.Open(ImportFiles.SelectedItems(FileCount))
wbName = Replace(CurrentBook.Name, ".xlsx", "")
CurrentBook.Activate
ActiveSheet.Name = wbName
CurrentBook.Close True
Next FileCount
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub

I had to tweak a couple of lines but this works beautifully. Thank you urdearboy.
Sub RenameSheet()
Dim CurrentBook As Workbook
Dim ImportFiles As FileDialog
Dim FileCount As Long 'Count of workbooks selected
Dim wbName As String
'Open File Picker
Set ImportFiles = Application.FileDialog(msoFileDialogOpen)
With ImportFiles
.AllowMultiSelect = True
.Title = "Pick Files to Adjust"
.ButtonName = ""
.Filters.Clear
.Filters.Add ".xlsx files", "*.xlsx"
.Show
End With
Application.DisplayAlerts = False
Application.DisplayAlerts = False
'Cycle through books
For FileCount = 1 To ImportFiles.SelectedItems.Count
Set CurrentBook = Workbooks.Open(ImportFiles.SelectedItems(FileCount))
wbName = Replace(CurrentBook.Name, ".xlsx", "") ' had to rework this line to the original
CurrentBook.Activate
ActiveSheet.Name = wbName
CurrentBook.Close True
Next FileCount ' had to change this to FileCount to remove the error "invalid next control variable"
Application.DisplayAlerts = True
Application.DisplayAlerts = True
End Sub

Related

in the attached code i am able to fetch data from 1 file but i want to fetch the data from multiple excel files which i am selecting

In the below code i am able to fetch data from 1 file but i want to fetch the data from multiple excel files which i am selecting.
can anyone please help me how i can get through with it.
Sub CopySheet()
Application.ScreenUpdating = False
Dim flder As FileDialog
Dim FileName As String
Dim FileChosen As Integer
Dim wkbSource As Workbook
Dim wkbDest As Workbook
Set wkbDest = ThisWorkbook
OpenFile:
Set flder = Application.FileDialog(msoFileDialogFilePicker)
flder.Title = "Please Select an Excel File"
flder.InitialFileName = "c:\"
flder.InitialView = msoFileDialogViewSmallIcons
flder.Filters.Clear
flder.Filters.Add "Excel Files", "*.xlsm*"
MsgBox ("Select a folder and then a file to open.")
FileChosen = flder.Show
FileName = flder.SelectedItems(1)
Set wkbSource = Workbooks.Open(FileName)
wkbSource.Sheets("Sheet1").UsedRange.Copy
wkbDest.Sheets("Master").Cells(wkbDest.Sheets("Master").Rows.Count, "A").End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
Application.CutCopyMode = False
Application.ScreenUpdating = True
wkbSource.Close savechanges:=False
If MsgBox("Do you want to open another workbook?", vbYesNo) = vbYes Then GoTo OpenFile
End Sub
Please, test the next updated code:
Sub CopySheet()
Dim flder As FileDialog, FileName As String, FileChosen As Integer
Dim wkbSource As Workbook, wkbDest As Workbook, i As Long
Set wkbDest = ThisWorkbook
OpenFile:
Set flder = Application.FileDialog(msoFileDialogFilePicker)
flder.Title = "Please Select Excel files"
flder.InitialFileName = "c:\"
flder.InitialView = msoFileDialogViewSmallIcons
flder.Filters.Clear
flder.Filters.Add "Excel Files", "*.xlsm" 'no need of ending *. Nothing can come after xlsm...
MsgBox ("Select a folder and then files to open and process.")
flder.AllowMultiSelect = True
FileChosen = flder.Show
If FileChosen = -1 Then
Application.ScreenUpdating = False
For i = 1 To flder.SelectedItems.count
FileName = flder.SelectedItems(i)
Set wkbSource = Workbooks.Open(FileName)
wkbSource.Sheets("Sheet1").UsedRange.Copy
wkbDest.Sheets("Master").cells(wkbDest.Sheets("Master").rows.count, "A").End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
Application.CutCopyMode = False
wkbSource.Close savechanges:=False
Next i
End If
Application.ScreenUpdating = True
If MsgBox("Do you want to process other workbooks?", vbYesNo) = vbYes Then GoTo OpenFile
End Sub

User Selection (workbook and sheet name) then Copy and Paste

Is there a way to make it where user selects which sheet to copy from, after they opened file?
I'd like to do this because there may be multiple sheets with same format, but have different names.
Example:
Original workbook named VSC (Contains sheets Compare, Plot)
Secondary workbook named SF (Contains sheets Results1, Results2, Results3)
User clicks button on VSC, and file dialog opens, and user selects SF in a certain directory, then asks user to select which sheet to choose from - user chooses Results2 sheet, copies the data (Range"B2:B5"), then pastes it back to Compare sheet.
Would this be possible? I am not sure how to start.
Current code that asks user to select SF workbook:
Sub GetFilePath()
Dim objFSO as New FileSystemObject
Set myFile = Application.FileDialog(msoFileDialogOpen)
With myFile
.Title = "Choose File"
.AllowMultiSelect = False
If .Show <> -1 Then
Exit Sub
End If
FileSelected = .SelectedItems(1)
End With
Here is one approach. You type in the sheet name. Adjust copy and paste ranges to suit.
Sub GetFilePath()
Dim objFSO As New FileSystemObject, w As String, wb As Workbook
Application.ScreenUpdating = False
Set myFile = Application.FileDialog(msoFileDialogOpen)
With myFile
.Title = "Choose File"
.AllowMultiSelect = False
If .Show <> -1 Then
Exit Sub
End If
Set wb = Workbooks.Open(.SelectedItems(1))
End With
w = InputBox("Enter sheet name")
If SheetExists(w) Then
wb.Sheets(w).Range("B2:B5").Copy
ThisWorkbook.Sheets("Compare").Range("A1").pastespecial xlvalues
Else
MsgBox "Sheet not found"
End If
wb.Close False
Application.ScreenUpdating = True
End Sub
Function SheetExists(s As String) As Boolean
Dim x
On Error GoTo NextSheet
x = ActiveWorkbook.Sheets(SheetName).Name
SheetExists = True
Exit Function
NextSheet:
SheetExists = False
End Function
Once you have your workbook open, you can enumerate the sheets by name and populate a pick list on a sheet in the VSC workbook...
Here is a different approach to your question. It is using a Timer after opening the new Workbook to ask you every 10 seconds if you are on the sheet you want to copy from. If you answer "Yes" it will copy. If you answer "no" it will restart the 10 second timer.
Sub GetFilePath()
Set MyFile = Application.FileDialog(msoFileDialogOpen)
With MyFile
.Title = "Choose File"
.AllowMultiSelect = False
If .Show <> -1 Then
Exit Sub
End If
FileSelected = .SelectedItems(1)
End With
Set newWk = Workbooks.Open(FileSelected, , True)
'Open Selected Workbook and check in 10 seconds for Selected Sheet Name
Application.OnTime Now + TimeValue("00:00:10"), "CheckForSheet"
End Sub
Private Sub CheckForSheet()
Dim SheetName As String
SheetName = ActiveSheet.Name
answer = MsgBox("Is This the Sheet to copy from: " & SheetName & "?", vbYesNo + vbQuestion, "Copy Data?")
If answer = vbYes Then
'ThisWorkbook is the workbook with the Macro/VBA code
'ActiveWorkbook is the workbook where you are selecting the Sheet to copy from
ActiveWorkbook.Sheets(SheetName).Range("B2:B5").Copy
ThisWorkbook.Sheets("Compare").Range("C1:C4").PasteSpecial
Else
'Check Again in 10 Seconds
Application.OnTime Now + TimeValue("00:00:10"), "CheckForSheet"
End If
End Sub

excel VBA 1004 error when copying multiple tabs into one tab from a folder

I am getting a 1004 error when I try and combine workbook pages into one master document. The code works correctly on my device, but when I attempt to run the code on my friends device it throw a 1004 error. I believe he is on excel 2013, I am on excel 2016. Is there any way to convert my code into something that can be used on both devices?
Sub CombineSheets()
Dim sPath As String
Dim sFname As String
Dim wBk As Workbook
Dim wSht As Variant
Application.EnableEvents = False
Application.ScreenUpdating = False
sPath = InputBox("Enter a full path to workbooks")
ChDir sPath
sFname = InputBox("Enter a filename pattern")
sFname = Dir(sPath & "\" & sFname & ".xl*", vbNormal)
wSht = InputBox("Enter a worksheet name to copy")
Do Until sFname = ""
Set wBk = Workbooks.Open(sFname)
Windows(sFname).Activate
Sheets(wSht).Copy Before:=ThisWorkbook.Sheets(1)
wBk.Close False
sFname = Dir()
Loop
ActiveWorkbook.Save
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
This works correctly when I run it, prompts for the folder location, asks which files it should copy from (usually *), and then copies from specifically the worksheet name entered.
Realistically all I need is code that can extract one worksheet from several hundred excel files and combine them into one master document. being able to pick and choose which worksheets would just be a bonus.
Thank you!
Like Mat's Mug said, you should really validate you inputs.
Did your co-worker add a "\" at the end of the path? Does the Path even exist?
Test to make sure that the sheet exists in the file that you are copying from, with something like this:
Function SheetExists(Name As String, Optional Workbook As Excel.Workbook = Nothing) As Boolean
If Workbook Is Nothing Then Set Workbook = ThisWorkbook.Application.ActiveWorkbook
On Error Resume Next
If Workbook.Worksheets(Name).Name <> vbNullString Then
End If
If Err.Number = 0 Then SheetExists = True
On Error GoTo 0
End Function
Here is your code with the noted changes:
Sub CombineSheets()
Dim sPath As String
Dim sFname As String
Dim wBk As Workbook
Dim sSht As String
Application.EnableEvents = False
Application.ScreenUpdating = False
sPath = InputBox("Enter a full path to workbooks")
'Use the FolderPicker to verify the path
With Application.FileDialog(msoFileDialogFolderPicker)
If .Show Then sPath = .SelectedItems(1)
End With
'ChDir sPath
sFname = InputBox("Enter a filename pattern")
sFname = Dir(sPath & "\" & sFname & ".xl*", vbNormal)
sSht = InputBox("Enter a worksheet name to copy")
Do Until sFname = ""
Set wBk = Workbooks.Open(sFname)
'Windows(sFname).Activate
If SheetExists(sSht, wBk) Then
wBk.Sheets(sSht).Copy Before:=ThisWorkbook.Sheets(1)
End If
wBk.Close False
sFname = Dir()
Loop
'ActiveWorkbook.Save
ThisWorkbook.Save
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
The bigger question is, are the Sheets the same size? Old .xls files only have 65536 rows, where 2007+ .xlsx files go up to 1048576 rows.
You can't mix the two different worksheets. In that case, you need to copy all of the cells from one sheet to the other.
wBk.Sheets(sSht).Cells.Copy
ThisWorkbook.Sheets.Add Before:=ThisWorkbook.Sheets(1)
ThisWorkbook.Sheets(1).Paste

Copy Sheet to Another Workbook - Path Error

I am trying to write a code to copy a worksheet, to an open workbook. But I am getting a path error at the end.
The code looks like this right now;
Sub Storyboard_Ekle()
Dim DosyaSec As Office.FileDialog
Set DosyaSec = Application.FileDialog(msoFileDialogFilePicker)
With DosyaSec
.AllowMultiSelect = False
.Title = "Lütfen yeni eklenecek Storyboard dosyasini seçiniz."
.Filters.Clear
.Filters.Add "Excel Macro-Enabled Workbook", "*.xlsm"
.Filters.Add "Excel Workbook", "*.xlsx"
.Filters.Add "All Files", "*.*"
If .Show = True Then
YeniSB = .SelectedItems(1)
End If
Dim YeniStoryBoard As Workbook
Dim AnaDosya As Workbook
Dim YeniStoryBoard_Sheet As Worksheet
Dim AnaDosya_Sheet As Worksheet
Application.ScreenUpdating = False
Set AnaDosya = ThisWorkbook
YeniStoryBoard.Sheets("Storyboard").Copy After:=ThisWorkbook.Sheets("Kunye") '-> This gives error
YeniStoryBoard.Close
Set YeniStoryBoard_isim = Sheets("Storyboard")
YeniStoryBoard_isim.Name = "StoryboardXXYYZZ"
End With
End Sub
I am going to make some modifications on the code onwards, but this doesn't work properly. :(
Any suggestions?
Here is one-line code to solve your case:
Public Sub TestMe
ThisWorkbook.Worksheets("Storyboard").copy after:= ThisWorkbook.Worksheets("Kunye")
End Sub
It should work. Then start checking what does not work in your case line by line. I guess that the problem is that after Dim YeniStoryBoard As Workbook you do not set it. Thus, it is Nothing.

VBA- working on multiple files

I'm working on a project in which I would like to have: browsing through files and selecting which to work with, copying and opening those workbooks from destination where their copies were created, then creating a new workbook(excel file) and copying information to it, which every workbook opened earlier would be in a separate sheet.
I have already done browsing through the files but I find it hard to go next.
That's the sample code I have by far.
Public Sub CommandButton1_Click()
Dim i As Integer
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = True
.Title = "Please select the file."
.Filters.Clear
.Filters.Add "All Files", "*.*"
If .Show = True Then
For i = 1 To fd.SelectedItems.Count
ListBox1.AddItem fd.SelectedItems(i)
Next
End If
End With
End Sub
It's just a matter of iterating through the workbooks.
Dim v as variant
If .Show = True Then
For Each v In fd.SelectedItems
'check if this is a valid workbook
Set WB = Workbooks.Open(v)
'Your code here
WB.Close savechanges:=False
Next v
End If