Bulk rename worksheets to workbook (file) names in specfic folder - excel

I have 90 Excel sheets in a folder: each Excel file has a unique name (company number) and contains only one worksheet. However the sheet name is generically named to 'Sheet1' in all files. Is there a VBA code that can rename all these sheets in this folder to their respective file name, minus the '.xlsx'?
Basically I want to combine all sheets to one file (I already have that VBA script). However before I can proceed with that, I have to rename all excel sheet names to their unique identifier (which is the file name).
I already looked online, but didn't see this script yet or saw this script for similar other purposes. Thanks in advance!

I found a solution online, credits to user VoG on https://www.mrexcel.com/forum/excel-questions/660913-vba-code-bulk-rename-first-worksheet-dependent-workbook-name.html
This is the solution. Change MyFolder = "C:\example" to respective folder
Sub RenSheets()
Dim MyFolder As String
Dim MyFile As String
Dim wbname As String
MyFolder = "C:\example"
MyFile = Dir(MyFolder & "\*.xls")
Application.ScreenUpdating = False
Do While MyFile <> ""
Workbooks.Open Filename:=MyFolder & "\" & MyFile
With ActiveWorkbook
wbname = Left(.Name, InStr(.Name, ".") - 1)
.Sheets(1).Name = wbname
.Close savechanges:=True
End With
MyFile = Dir
Loop
Application.ScreenUpdating = True
End Sub

Related

Problem with exporting data from the latest file

I have a problem with my macro in Excel VBA. This is my first macro... So, I have the first file, where is the button, which is opening the another file. In this another file I made an UserForm, where user cant check, on which area will do "something". And there is the start of my problems. I want, that when the user check the area, open the latest file in folder of this area xd so i foung the code and it works, next file opens, the I want split a part of this latest document where is the number of something and it also works, but I want to add this numba()+1 to this file, where the userform with possibility of checkig area is, alsa I want to after this splitting and export numba() to another file close this file, from I exported the numba(), but when I do Workbooks(My Path&Latest File).Close SaveChanges=False, Vba shows a mistake. So Can you help me with this problem? How to export this numba+1 from opening latest file to this accurate, where I work in fact?
Or maybe do you have any idea, how can I export only name of this latest file without opening it? Then i will export onlu name, split it and make the next number for this document ... Below I add codes, thanks for your help :)
Private Sub CommandButton1_Click()
Dim MyPath As String
Dim MyFile As String
Dim LatestFile As String
Dim LatestDate As Date
Dim LMD As Date
MyPath = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"
MyFile = Dir(MyPath & "*.xlsx", vbNormal)
If Len(MyFile) = 0 Then
MsgBox "No files were found...", vbExclamation
Exit Sub
End If
Do While Len(MyFile) > 0
LMD = FileDateTime(MyPath & MyFile)
If LMD > LatestDate Then
LatestFile = MyFile
LatestDate = LMD
End If
MyFile = Dir
Loop
Workbooks.Open MyPath & LatestFile
Dim numba() As String
numba() = Split(Range("I6"), "-")
Call NAZWA
Sub NAZWA()
This.Workbooks.Activate
Worksheets("Tabelle1").Activate
Range("I6") = "xx-xxxx-"
End Sub
Please, try Workbooks(LatestFile).close
Workbooks collection keeps only the workbooks name, not their full name...
Use this technique:
Dim MyOpenWb As Workbook
Set MyOpenWb = Workbooks.Open(MyPath & LatestFile) 'set a reference to the opened workbook for later use
'access any worsheet/cell in that workbook like
MyOpenWb.Worksheets("Sheet1").Range("A1").Value = "write into Sheet1 cell A1"
'make sure every Range/Cells/Columns/Rows has a workbook/worksheet specified
'otherwise it is not clear where Excel should look for Range("I6")
Dim numba() As String
numba() = Split(MyOpenWb.Worksheets("Tabelle1").Range("I6"), "-")
'do your stuff here …
'Close it
MyOpenWb.Close SaveChanges:=True 'or False
When ever you open a workbook set it to a variable eg MyOpenWb. You can then use this variable to access the workbook and also to close it. So you never have to deal with it's name or path again once it is open.
Avoid using .Select and .Activate instead access a range by naming its workbook and worksheet like below:
ThisWorkbook.Worksheets("Tabelle1").Range("I6").Value = "xx-xxxx-"
You might benefit from reading
How to avoid using Select in Excel VBA.

Looping code error-Excel says that it can't find the file

I'm trying to write a code that will refresh all workbooks starting with 'FY' in a folder. With the current code, the first two workbooks refresh, but when it comes to the third workbook, I get this error:
Sorry, we couldn't find FY20 11-15.xlsm\FY20 1-5.xlsm. Is it possible it was moved, renamed or deleted?"
The path to the workbook is "C:\Documents\Database\Sales".
Here's the code:
Sub refreshdata()
Dim file As String
Dim book As String
file = Application.ThisWorkbook.Path
book = Dir(file & "\FY*.xlsm")
Do While file <> ""
Dim wb As Workbook
Set wb = Workbooks.Open(file & "\" & book)
Call Refresh
wb.Close savechanges:=True
file = Dir
Loop
End Sub
You named your variables not clearly and file contains actually a path file = Application.ThisWorkbook.Path therefore you mixed everything up. Get your variable names more meaningful! Make sure your variables are well named after what content they contain or you confuse yourself.
Sub refreshdata()
Dim Path As String
Path = Application.ThisWorkbook.Path
Dim FileName As String
FileName = Dir(Path & "\FY*.xlsm")
Do While FileName <> vbNullString
Dim wb As Workbook
Set wb = Workbooks.Open(Path & "\" & FileName)
Call Refresh
wb.Close SaveChanges:=True
FileName = Dir
Loop
End Sub
What was wrong?
Here file = Dir you set your file variable which actually was the path to filename. And in the next iteration of the loop Set wb = Workbooks.Open(file & "\" & book) is twice a filename, the new filename in file and the old in book.

Excel VBA Dir() Error when file type changes

I'm trying to better understand the Dir function. I have a Dir loop to take action on all .csv files in the directory, but when the loop comes across another file type, like .txt, it will error instead of moving on to the next .csv. item.
This is the relevant portion of my code.
strSourceExcelLocation = "\\rilinfs001\Interdepartmental\Billings & Deductions\Billing Coordinators\MCB Reports\East\Monthly Quality MCBs (CMQ & SECMQ)\2019\Individual_Reports\" & fldr & "\"
strWorkbook = Dir(strSourceExcelLocation & "*.csv*")
Do While Len(strWorkbook) > 0
'Open the workbook
Set wbktoExport = Workbooks.Open(Filename:=strSourceExcelLocation & strWorkbook)
'Export all sheets as single PDF
Call Export_Excel_as_PDF(wbktoExport)
'Get next workbook
strWorkbook = Dir
'Close Excel workbook without making changes
wbktoExport.Close False
Loop
So if there are only .csv files in the directory, then this works fine. When it comes across another file type, an error occurs.
The error is on line
strWorkbook = Dir
Run-time error 5: Invalid procedure call or argument
Am I missing something with the way I use the wildcards in the .csv at the beginning?
Thank you
Solved my issue.
The problem seems to have been because when I called another procedure, I had another Dir in that sub to create a new folder if one didn't already exist. So basically I had a Dir in a Dir, which apparently is bad.
I moved the folder creation part to the very beginning of my procedure, so it is executed before I begin the Dir for looping through all the CSV files.
Option Explicit
Sub Loop_Dir_for_Excel_Workbooks()
Dim strWorkbook As String, wbktoExport As Workbook, strSourceExcelLocation As String, fldr As String, strTargetPDFLocation As String, d As String
strTargetPDFLocation = "\\nhchefs001\Accounting\IMAGING\BILLINGS & DEDUCTIONS\EAST MCB FILES\"
'***** Creating a folder to save the PDFs in. Naming the folder with today's date *****
d = Format(Date, "mm-dd-yyyy")
strTargetPDFLocation = "\\nhchefs001\Accounting\IMAGING\BILLINGS & DEDUCTIONS\EAST MCB FILES\" & d & "\"
If Len(Dir(strTargetPDFLocation, vbDirectory)) = 0 Then MkDir strTargetPDFLocation
fldr = InputBox("Input the EXACT Folder Name that you want to create PDFs for")
strSourceExcelLocation = "\\rilinfs001\Interdepartmental\Billings & Deductions\Billing Coordinators\MCB Reports\East\Monthly Quality MCBs (CMQ & SECMQ)\2019\Individual_Reports\" & fldr & "\"
'Search all Excel files in the directory with .xls, .xlsx, xlsm extensions
strWorkbook = Dir(strSourceExcelLocation & "*.csv")
Do While Len(strWorkbook) > 0
'Open the workbook
Set wbktoExport = Workbooks.Open(Filename:=strSourceExcelLocation & strWorkbook)
'Export all sheets as single PDF
Call Export_Excel_as_PDF(wbktoExport, strTargetPDFLocation)
'Close Excel workbook without making changes
wbktoExport.Close False
'Get next workbook
strWorkbook = Dir
Loop
End Sub
Try to hardcode the path and give it a try again. Probably the error is something really small in the hardcoding. E.g., in the code below, replace C:\Users\username\Desktop\AAA\ with the path of the file. Then run it. Do not forget the last \. It should work:
Sub TestMe()
Dim workbookPath As String
workbookPath = Dir("C:\Users\username\Desktop\AAA\" & "*.csv")
Do While Len(workbookPath) > 0
Debug.Print workbookPath
workbookPath = Dir
Loop
End Sub

How to loop and open all csv files in my current folder in VBA

I randomly create a new folder on my desktop, in this folder I have one template file with .xlsm extension, which contains my VBA code. Meanwhile I have several csv files saved in the same folder with my raw data.
The purpose is looping through all those csv files one by one, open it, and copy some data and paste to my template file(I know how to do this part) from it and close it after all operations are done.
Currently I meet a problem about how to loop through my folder and open those csv one by one. I didn't set a specific folder name, since I want to share it with other people to use,therefore I use Application.ActiveWorkbook.Path to get the path for my current folder.
Here is my code:
Option Explicit
Sub Range_End_Method()
Dim Dir As String
Dim i As String
Application.ScreenUpdating = False
Dir = Application.ActiveWorkbook.Path & "\"
For Each i In Dir.Files
Debug.Print i.Name
If (i.Name Like "*.csv") Then
Workbooks.Open (i.Path)
End If
Next
End Sub
I'm guessing you want to use the Dir function. To use that, make a call to it, specifying folder and file type in the first call, then call it empty until it returns an empty string. Like this:
Folder = Dir(Application.ActiveWorkbook.Path & "\*.csv")
Do While Folder <> ""
Debug.Print Folder
Workbooks.Open Folder
Folder = Dir()
Loop
You can use this function and macro.
Juste replace MsgBox (myFile + "OK") by the action you want to execute.
FUNCTION
Function ClasseurOuvert(NomFich)
On Error Resume Next
Workbooks(NomFich).Activate
If Err <> 0 Then Workbooks.Open FileName:=NomFich
On Error GoTo 0
End Function
MACRO
Sub LoopFiles()
Dim myPath As String, myFile As String
myPath = Application.ActiveWorkbook.Path & "\"
myFile = Dir(myPath & "\*.*")
Do While myFile <> "" And myFile Like "*.csv"
Call ClasseurOuvert(myPath & "\" & myFile)
With Workbooks(myFile)
MsgBox (myFile + "OK")
End With
Workbooks(myFile).Save
Workbooks(myFile).Close
myFile = Dir()
Loop
End Sub

Using a wildcard to open an excel workbook

I want to use a wildcard to open a workbook stored in the same folder as my macro workbook. In the folder is a file named 302113-401yr-r01.xlsm. Here is my code:
Workbooks.Open filename:=ActiveWorkbook.Path & "\302113*.xlsm"
However, it tells me that there is no such file. Any advice?
We cannot open a file using a wildcard - imagine the chaos if we could!
You'll need to use Dir(ActiveWorkbook.Path & "\302113*.xlsm") to loop through the files that this returns. If there will only be one then just use this function once:
Dim sFound As String
sFound = Dir(ActiveWorkbook.Path & "\302113*.xlsm") 'the first one found
If sFound <> "" Then
Workbooks.Open filename:= ActiveWorkbook.Path & "\" & sFound
End If
Dir Function :tech on the net
From my experience this works if you have the wildcard/asterix as the last symbol in the string and if there is only one file. Try doing:
Workbooks.Open filename:=ActiveWorkbook.Path & "\302113*"
For example I am using:
Workbooks.Open Filename:="X:\business\2014\Easy*"
and it works.
You can open files using the wildcard, but only with UNC paths for some reason.
For example :
Set xlFile = xlObj.WorkBooks.Open("\\yourServerHere\dataAutomation\*.xlsx")
I'm not that experienced yet with Excel but the following works well for me for using wildcards in filenames to open files. This example requires all files to be in the same directory/folder. Yes, it is pretty simplistic.
Sub using_wildcards_to_open_files_in_excel_vba()
Dim mypath As String
Dim sFilename As String
'Suppose you have three files in a folder
' Named blank.xlsx,, ex1_939_account.xlsx, and ex1_opt 5.xlsx
'Manually open the blank.xlsx file
'The following code lines will open the second two files before closing the previously opened file.
ActiveWorkbook.Activate
mypath = ActiveWorkbook.Path
'opening xlsx file with name containing "939" and closing current file
mypath = mypath & "\*939*.xlsx"
'MsgBox mypath 'Checking
sFilename = Dir(mypath)
'MsgBox sFilename 'Checking
ActiveWorkbook.Close savechanges:=False
Workbooks.Open Filename:=sFilename
ActiveWorkbook.Activate
mypath = ActiveWorkbook.Path
'opening xlsx file with name ending in "opt 5" and closing current file
mypath = mypath & "\*opt 5.xlsx"
'MsgBox mypath 'Checking
sFilename = Dir(mypath)
'MsgBox sFilename 'Checking
ActiveWorkbook.Close savechanges:=False
Workbooks.Open Filename:=sFilename
End Sub

Resources