#1
|
|||
|
|||
Rename Files in a Folder and Overwrite if File Exists
Hi
I have a macro that renames all files in a folder that begin with the litter "I": Sub RenameFile() Dim file Dim path As String path = "C:\DOCUMENTS\FOLDER" file = Dir(path & "I*.docx") 'rename the files with the I in front to remove the I Dim NewName As String Do While file <> "" NewName = Mid(file, 2) Name path & file As path & NewName file = Dir() Loop End Sub This works well and does what I expect, however, if the NewName file already exists, I just get an error that it already exists. Can someone please help with extra code which will overwrite the NewName file if it already exists in the folder. Thank you very much |
#2
|
|||
|
|||
Double post...
|
#3
|
|||
|
|||
Before running the code, click Tools > References… in the Visual Basic Editor and make sure that “Microsoft Scripting Runtime” is checked.
Code:
Sub RenameFile() ' Before running the code, click Tools > References in the Visual Basic Editor and ' make sure that "Microsoft Scripting Runtime" is checked. Dim strPath As String Dim objFile As File Dim objFolder As Folder Dim objFSO As Scripting.FileSystemObject ' Put your path here: strPath = "C:\DOCUMENTS\FOLDER" Set objFSO = CreateObject("Scripting.FileSystemObject") If objFSO.FolderExists(strPath) Then Set objFolder = objFSO.GetFolder(strPath) ' Loop through all files in the folder: For Each objFile In objFSO.GetFolder(strPath).Files ' If the file starts with the letter I and is a Word file... If InStr(objFile.Name, "I") = 1 And InStr(objFile.Name, ".docx") <> 0 Then '...then copy it with the I removed from the name, overwriting ' an existing version, if necessary: objFSO.CopyFile objFolder.path & "\" & objFile.Name, objFolder.path & "\" & Mid(objFile.Name, 2), True ' Delete the original "I" version: objFSO.DeleteFile (objFile.path) End If Next objFile End If End Sub |
#4
|
|||
|
|||
Thank you Peterson, this is exaclty what I need.
|
|
Similar Threads | ||||
Thread | Thread Starter | Forum | Replies | Last Post |
Error Handler If User Does Not Want to Overwrite File | ChrisOK | Excel Programming | 4 | 04-03-2020 08:31 PM |
Need excel macro which helps to rename the files within the folder | ganesang | Excel Programming | 1 | 02-04-2019 11:13 PM |
need to overwrite folder permissions from previous office version | gmee | Outlook | 0 | 02-19-2018 10:06 AM |
Normal file already exists | cryptogram | Word | 2 | 09-21-2015 08:56 PM |
Word does not ask do i want to overwrite a file on saving a file | sam2149 | Word | 2 | 03-24-2014 04:18 AM |