VBA to rename a folder (not file)

AndrewKent

Well-known Member
Joined
Jul 26, 2006
Messages
889
Hi all,

I have a folder with multiple sub folders that are all "# Jan", "# Feb" ect. and rather than change these manually I am looking to write a VBA script that will loop through each sub folder and rename them to "01 Jan", "02 Feb" ect.

Any advice?

Andy
 

Excel Facts

Square and cube roots
The =SQRT(25) is a square root. For a cube root, use =125^(1/3). For a fourth root, use =625^(1/4).
This is the code to rename. Are you Ok with the loop code?

Code:
Sub RenameFolder()

Dim sOld As String, sNew As String


    'change values as required
    sOld = "C:\Test"
    sNew = "C:\TestNew"
    
    'change name
    Name sOld As sNew
    
End Sub
 
Upvote 0
After re-reading, it wasn't as simple as I thought:

This will do as you ask, replacing the "#" with the month number of the 3 chr short month name

Change the InitialPath variable as required

Code:
Sub RenameSubfolders()


Dim FileSystem As Object, Folder As Object, SubFolder As Object
Dim InitialPath As String
Dim sOld As String, sNew As String


    InitialPath = "C:\Test\Test2\"
    
    Set FileSystem = CreateObject("Scripting.filesystemobject")
    Set Folder = FileSystem.GetFolder(InitialPath)
    
    For Each SubFolder In Folder.subfolders
        sOld = SubFolder.Name
        If InStr(1, sOld, "#") > 0 Then
            sNew = Replace(sOld, "#", Format(Month("01/" & Right(sOld, 3)), "00"))
            Name InitialPath & sOld As InitialPath & sNew
        End If
    Next SubFolder


End Sub
 
Upvote 0

Forum statistics

Threads
1,223,911
Messages
6,175,324
Members
452,635
Latest member
laura12345

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top