Hello,
I was able to get this code to work at one point but now I am having problems.
The goal of the code is to allow the user to point to a folder that will contain various Excel files named Book1, Book2, Book3.... rename the files based on the contents in A1 and then close the files.
The code is allowing me to select a folder and select all of the files in the folder. Next the code appears to run and says Task Complete! but the file names are not changed.
I have attached 3 test files that are currently in the folder I am selecting.
Any help would be greatly appreciated.
I was able to get this code to work at one point but now I am having problems.
The goal of the code is to allow the user to point to a folder that will contain various Excel files named Book1, Book2, Book3.... rename the files based on the contents in A1 and then close the files.
The code is allowing me to select a folder and select all of the files in the folder. Next the code appears to run and says Task Complete! but the file names are not changed.
I have attached 3 test files that are currently in the folder I am selecting.
Any help would be greatly appreciated.
Code:
Sub LoopAllExcelFilesInFolder()
'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them
'SOURCE: www.TheSpreadsheetGuru.com
Dim WB As Workbook
Dim myPath As String
Dim myfile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFilePicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = True
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & ""
End With
'In Case of Cancel
NextCode:
'myPath = "C:\Users\Callie"
'If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*.xlsx*"
'Target Path with Ending Extention
myfile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myfile <> ""
'Set variable equal to opened workbook
Set WB = Workbooks.Open(Filename:=myPath & myfile)
'Ensure Workbook has opened before moving on to next line of code
DoEvents
Dim newFileName As String
newFileName = ActiveSheet.Range("A1").Value
'Save and Close Workbook
WB.Close SaveChanges:=True
'Rename with new file name
Name myPath & myfile As myPath & newFileName & Mid(myfile, InStrRev(myfile, "."))
'Ensure Workbook has closed before moving on to next line of code
DoEvents
'Get next file name
myfile = Dir
Loop
'Message Box when tasks are completed
MsgBox "Task Complete!"
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub