I have a vba code that searches a folder and then in excel it will create a list of all…
- User
I have a vba code that searches a folder and then in excel it will create a list of all the files in the folder with links to each file. Is there a VBA code that can rename a file in a folder.
- Assistant
Yes, the following VBA code can rename a file in a folder:
codeSub RenameFile() Dim oldName As String Dim newName As String oldName = "path\to\old\name\of\file" newName = "path\to VBA.FileSystem.Name oldName, newName End SubIn this code, you need to specify the old name of the file with its full path and also provide a new name with a full path. The VBA FileSystem object's Name method will rename the old file with the new name specified.
- User
My Vba code that lists all files in a folder puts the list into column A. Each of the file names also has a hyperlink to the file. I n column B for the corresponding file in column a, I want to type the word Processed. When the word processed is entered in column B I want another VBA code that will go to the file indicated in column A and append to the beginning of the file name the word PRO in capital letters
- Assistant
Here's a VBA code that will accomplish what you're looking for:
codeSub RenameFile() Dim rng As Range Dim cell As Range Dim fileName As String Dim filePath As String Dim processedFlag As String Set rng = ActiveSheet.UsedRange.Columns("A:B") For Each cell In rng.Cells If cell.Column = 1 Then ' Check if the cell has a hyperlink If cell.Hyperlinks.Count > 0 Then filePath = cell.Hyperlinks(1).Address fileName = VBA.FileSystem.GetFileName(filePath) End If ElseIf cell.Column = 2 Then ' Check for the processed flag processedFlag = Trim(cell.Value) If processedFlag = "Processed" Then ' Rename the file with PRO prefix VBA.FileSystem.Rename filePath, VBA.FileSystem.GetParentFolderName(filePath) & "\PRO" & fileName End If End If Next cell End Sub