mehidy1437
Active Member
- Joined
- Nov 15, 2019
- Messages
- 348
- Office Version
- 365
- 2016
- 2013
- Platform
- Windows
- Mobile
- Web
Hi I have got this code on the web & its working fine.
I just need to add a condition is, while renaming the files, if its found that the same name already exists in the folder, then it will add an additional number at the end of the new name.
Please help me with this.
I just need to add a condition is, while renaming the files, if its found that the same name already exists in the folder, then it will add an additional number at the end of the new name.
Please help me with this.
VBA Code:
Sub RenameAllFilesInaFolder()
'Set a reference to Microsoft Scripting Runtime by using
'Tools > References in the Visual Basic Editor (Alt+F11)
'change the file format in below xls or xlsx
Dim objFile As Scripting.File
Dim objFolder As Scripting.Folder
Dim owbk As Workbook, twbk As Worksheet, ws As Worksheet
Dim cRow As Integer, fName As String, fol As String
Dim v As String, fv As String
Application.ScreenUpdating = False
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Show
On Error Resume Next
fol = .SelectedItems(1)
Err.Clear
On Error GoTo 0
End With
If fol = "" Then Exit Sub
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(fol)
For Each objFile In objFolder.Files
Set twbk = ThisWorkbook.Sheets("Sheet1")
cRow = twbk.Range("A" & Rows.Count).End(xlUp).Row
Set owbk = Workbooks.Open(objFile)
Set ws = owbk.Sheets(1)
'v = ws.[C3].Value 'file name from cell c3
v = "SS_" & ws.[C3].Value 'file name withe prefix and cell c3
twbk.Range("A" & cRow + 1).Value = v 'Change as need
fv = v & ".xls" 'file format see below to save option for xls and xlsx
fName = objFolder & "\" & fv
'save option for xls
ws.SaveAs Filename:=fName, FileFormat:=xlExcel8, CreateBackup:=False
Windows(fv).Close False
Kill objFile
Next objFile
Application.ScreenUpdating = True
Set ws = Nothing
Set owbk = Nothing
Set twbk = Nothing
Set objFolder = Nothing
Set objFSO = Nothing
End Sub