How do I write a VBA code to rename all folders under a root folder?

前端 未结 1 985
南笙
南笙 2021-01-16 04:12

I\'m very new to VBA and have been messing around with a few codes for work. Essentially, I have a folder that contains 1000+ folders with different names--and I need to ren

相关标签:
1条回答
  • 2021-01-16 04:50

    There are 2 ways to go about this. The first (and much slower one) is to open each file with the old name, save as with the new name, and then move to the next.

    I would reccomend the scripting style approach, using a file system object you can move files (rename them) within a loop.

    Presuming the old and new file names have a relative path with them from some parent folder:

    Dim fso As New FileSystemObject, ParentFolder as string
    ParentFolder = "C:\Users\Me\ThisProject\"
    
    For i = 2 To Sheets(1).Range("a1").End(xlDown).Row
        new_name = Left(Sheets(1).Cells(i, 1).Value, Len(Sheets(1).Cells(i, 1).Value) - Len(Sheets(1).Cells(i, 2).Value))
        new_name = new_name & Sheets(1).Cells(i, 3).Value
        old_name = Sheets(1).Cells(i, 1).Value
    
        'This will move (rename) the old file to the new one
        fso.MoveFile (ParentFolder & old_name), (ParentFolder & new_name)
    Next i
    
    0 讨论(0)
提交回复
热议问题