Search code examples
vbscriptfilenamesfile-rename

Need to rename multiple files via VBScript in a particular folder


I need to rename multiple files via VBScript in a particular folder

Example:

Change name to specific name with number convention such as Change Part1.csv to 31-AUG-20-1.csv and Part2.csv to 31-Aug-29-2.csv

Here 31-Aug-20 will remain same but with a incremental number. Therefore in below code i don't want to give new name i.e. 31-Aug-20-1.csv against each file rather it should change to 31-Aug-20(incremental numbering)

 Dim fso, folder, file, folderName, dict
    
    'Path
    folderName = "C:\User\desktop\ATL\"
    
    'Future FileName
    Set dict = CreateObject("Scripting.Dictionary")
    dict.Add "Part1.csv", "ATL-31-Aug-20-1.csv"
    dict.Add "Part2.csv", "ATL-31-Aug-20-2.csv"
    dict.Add "Part3.csv", "ATL-31-Aug-20-3.csv"
    dict.Add "Part4.csv", "ATL-31-Aug-20-4.csv"
    dict.Add "Part5.csv", "ATL-31-Aug-20-5.csv"
    dict.Add "Part6.csv", "ATL-31-Aug-20-6.csv"
    
    ' Create filesystem object and the folder object
    Set fso = CreateObject("Scripting.FileSystemObject")  
    Set folder = fso.GetFolder(folderName)  
    
    ' Loop over all files in the folder until the searchFileName is found
    For Each file In folder.Files
        If dict.Exists(file.Name) Then file.Name = dict(file.Name)
    Next

Solution

  • This code will rename the files with incremental numbering:

    Dim iCounter
    Dim folderName
    Dim fso, folder, file
    
    ' Path
    folderName = "C:\User\desktop\ATL\"
    
    ' Create filesystem object and the folder object
    Set fso = CreateObject("Scripting.FileSystemObject")  
    Set folder = fso.GetFolder(folderName)  
    
    iCounter = 1
    For Each file In folder.Files
        file.Name = "ATL-32-Aug-20-" & iCounter & ".csv"
        iCounter = iCounter + 1
    Next
    

    If you want to keep the number from the original file name (Part#.csv), you can add the following logic:

    Const vbTextCompare = 1
    Dim folderName
    Dim fso, folder, file
    Dim sNumber
    Dim sPrefix
    
    ' Path and prefix
    folderName = "C:\User\desktop\ATL\"
    sPrefix = "ATL-32-Aug-20-"
    
    ' Create filesystem object and the folder object
    Set fso = CreateObject("Scripting.FileSystemObject")  
    Set folder = fso.GetFolder(folderName)  
    
    For Each file In folder.Files
        ' Check for "Part" and ".csv" in file name
        If StrComp(Left(file.Name, 4), "Part", vbTextCompare) = 0 And StrComp(Right(file.Name, 4), ".csv", vbTextCompare) = 0 Then
            ' Extract number
            sNumber = Mid(file.Name, 5, Len(file.Name) - 8)
            ' Rename file
            file.Name = sPrefix & sNumber & ".csv"
        End If
    Next