Rename Files Using VBA (Easy Examples)

PHOTO EMBED

Fri Feb 07 2025 08:40:35 GMT+0000 (Coordinated Universal Time)

Saved by @acassell

Sub RenameTXTFiles()
    Dim FSO As Object
    Dim sourceFolder As Object
    Dim file As Object
    Dim folderPath As String
    Dim newName As String
    Dim counter As Integer
    
    ' Create a FileSystemObject
    Set FSO = CreateObject("Scripting.FileSystemObject")
    
    ' Specify the folder path (change this to your desired folder)
    folderPath = "C:\Users\sumit\Downloads\"
    
    ' Check if the folder exists
    If FSO.FolderExists(folderPath) Then
        Set sourceFolder = FSO.GetFolder(folderPath)
        
        ' Initialize counter
        counter = 1
        
        ' Loop through each file in the folder
        For Each file In sourceFolder.Files
            ' Check if the file has a .txt extension
            If LCase(FSO.GetExtensionName(file.Name)) = "txt" Then
                ' Create new name (you can modify this format as needed)
                newName = "NewFile_" & file.name & ".txt"
                
                ' Rename the file
                file.Name = newName
      
content_copyCOPY

https://trumpexcel.com/excel-vba/rename-files/