CodeItBetter Programming Another VB Programming Blog

How to Rename folder (in three ways)

Posted on October 21, 2011
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
'File/Folder Handling - How to Rename folder (in three ways)
'Using Name Statement:

Public Sub RenameFolderUsingName(ByVal sOldFolderName As String, ByVal sNewFolderName As String)
'Using Name on an open file produces an error. You must close an open
'file before renaming it. Name arguments cannot include multiple-character (*)
'and single-character (?) wildcards.
'If the Folder sNewFolderName already exists then it will produce an error
    Name sOldFolderName As sNewFolderName
End Sub
 
'Using FSO Method 1:

Public Sub RenameFolderUsingFSO(ByVal sOldFolderName As String, ByVal sNewFolderName As String)
'Set a reference to "Microsoft Scripting Runtime"
'If the Folder sNewFolderName already exists then it will overwrite
    Dim FSO As Scripting.FileSystemObject
    Set FSO = New Scripting.FileSystemObject
    FSO.CopyFolder sOldFolderName, sNewFolderName
    'It will produce error if any files from this folder is opened/locked
    FSO.DeleteFolder sOldFolderName, True
    Set FSO = Nothing
End Sub
 
'Using FSO Method 2:

Public Sub RenameFolderUsingFSO(ByVal sOldFolderName As String, ByVal sNewFolderName As String)
'Set a reference to "Microsoft Scripting Runtime"
'If the Folder sNewFolderName already exists then it will overwrite
    Dim FSO As Scripting.FileSystemObject
    Set FSO = New Scripting.FileSystemObject
    sNewFolderName = RemoveBackslash(sNewFolderName)
    FSO.GetFolder(sOldFolderName).Name = Mid$(sNewFolderName, InStrRev(sNewFolderName, "\") + 1)
    Set FSO = Nothing
End Sub
 
Public Function RemoveBackslash(ByVal sFolder As String)
    If Right$(sFolder, 1) = "\" Then
        RemoveBackslash = Left$(sFolder, Len(sFolder) - 1)
    End If
End Function
Comments (1) Trackbacks (0)
  1. Hi,

    But this solution will not work in Windows Vista machines with User Account Control(UAC) is set ON.

    Do you have any solution when UAC is ON?

    Regards

    Joseph


Reply

( Cancel )

 

No trackbacks yet.