How to rename files in a folder.
Q: Richard Bryant writes:
I have written the following code to change the name of files imported as .tif files from the county deed books for use by my Access program.
Private Sub Command2_Click()
Dim Path1 As String
Dim Path2 As String
Dim Filename As String
Dim NewBkPg As String
Path1 = “X:SpecialProjectsTOBAssessingRoxio29EAllDeedsCopy”
Path2 = “X:SpecialProjectsTOBAssessingRoxio29EAllDeedsFixed”
Filename = “Bk 22589 Pg 144.tif”
NewBkPg = Mid(Filename, 1, 2) & Mid(Filename, 4, 5) _
& Mid(Filename, 10, 2) & Mid(Filename, 13, 8)
Name Path1 & Filename As Path2 & NewBkPg
End Sub
This works as long as I insert the name of the file. Obviously not what I want as there are many hundreds of files. What I need to do is have the program look at the folder “AllDeedsCopy” and change all the filenames in it according to the formula, such as:
Do Until Path1 is empty
Filename = CurrentTopFilename
NewBkPg = Mid(Filename, 1, 2) _
& Mid(Filename, 4, 5) & Mid(Filename, 10, 2) _
& Mid(Filename, 13, 8)
Name Path1 & Filename As Path2 & NewBkPg
Loop
My knowledge of Basic seems to fail me to know how to write the code to get the program to look in Path1, take the top filename run it thru the conversion and loop to the top again until there are no files left to convert.
A: You can use components of the Scripting Runtime library to rename files; here is some sample code:
Public Function RenameFiles()
Dim fso As Scripting.FileSystemObject
Dim fld As Scripting.Folder
Dim fil As Scripting.File
Dim strDocsPath As String
Dim strNewFileName As String
Dim strDefault As String
Dim strTitle As String
Dim strPrompt As String
Dim lngCount As Long
lngCount = 0
strTitle = “Select folder”
strPrompt = “Select folder for changing file names”
strDefault = “D:DocumentsFigures”
strDocsPath = InputBox(prompt:=strPrompt, _
Title:=strTitle, Default:=strDefault)
Set fso = CreateObject(“Scripting.FileSystemObject”)
Set fld = fso.GetFolder(strDocsPath)
For Each fil In fld.Files
‘Check first character and extension (modify as
‘needed for your requirements)
If Left(fil.Name, 1) = “-” And _
Right(fil.Name, 3) = “tif” Then
‘Modify line below as needed for your requirements
strNewFileName = Mid(fil.Name, 9)
fil.Name = strNewFileName
lngCount = lngCount + 1
End If
Next fil
strTitle = “Files renamed”
strPrompt = lngCount & ” files in ” & strDocsPath & ” renamed”
MsgBox strPrompt, vbInformation, strTitle
End Function
The code requires a reference to the Scripting Runtime library. See the Scripting Runtime help file for help on the FileSystemObject; it can be downloaded from the Microsoft Web site at http://www.microsoft.com/downloads/details.aspx?FamilyID=01592C48-207D-4BE1-8A76-1C4099D7BBB9&displaylang=en (if that link is broken, search for Windows Script 5.6 Documentation).