Hello,
I'm trying to rename all files in a folder based on values in the file and then save them in a user selected folder.
Below is what I have so far. It is able to rename and save the file but I have to select the save folder through each loop.
Is there a way to select the destination folder once at the beginning and have the macro loop through every file in the folder to save and rename?
Any help would be appreciated. Thanks
I'm trying to rename all files in a folder based on values in the file and then save them in a user selected folder.
Below is what I have so far. It is able to rename and save the file but I have to select the save folder through each loop.
Is there a way to select the destination folder once at the beginning and have the macro loop through every file in the folder to save and rename?
VBA Code:
Function ChooseFolder1() As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(4)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = strPath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
ChooseFolder1 = sItem
Set fldr = Nothing
End Function
Sub payrollmacro1()
Dim wb As Workbook
Dim ws As Worksheet
Dim firstname As String
Dim lastname As String
Dim datefirst As String
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder("C:\Users\Private\Documents\Projects\PayrollTimeSheets")
For Each objFile In objFolder.Files
If objFile.Name Like "*Time-Card*" Then
Set wb = Workbooks.Open(objFile.path)
firstname = Workbooks(objFile.Name).Worksheets("Time Card").Range("C2")
lastname = Workbooks(objFile.Name).Worksheets("Time Card").Range("B2")
datefirst = Workbooks(objFile.Name).Worksheets("Time Card").Range("D2").Value
wb.SaveAs Filename:=ChooseFolder1 & "\" & Format(datefirst, "yyyymmdd") & "-" & firstname & lastname & "-" & "TimeCard" & ".xlsx", FileFormat:=51
wb.Close
End If
Next objFile
End Sub
Any help would be appreciated. Thanks