|
|
Title | Rename the files in a directory |
Description | This example shows how to rename the files in a directory in Visual Basic 6. |
Keywords | rename files |
Categories | Files and Directories, Utilities |
|
|
I needed it because Chapter 20 turned
into Chapter 19 in a book. I needed to rename Fig20-1.bmp to Fig19-1.bmp,
Fig20-2.cdr to Fig19-2.cdr, etc.
This program finds all the normal files in a directory and renames them,
replacing one string with another.
It uses Dir$ to list the files. It then uses Replace to replace occurrences of a string with another in the file name. It uses Name to rename the files. If a file's name doesn't contain the target string, it is not renamed.
|
|
Private Sub cmdGo_Click()
Dim i As Integer
Dim from_str As String
Dim to_str As String
Dim dir_path As String
Dim old_name As String
Dim new_name As String
On Error GoTo RenameError
from_str = txtFromString.Text
to_str = txtToString.Text
dir_path = txtDirectory.Text
If Right$(dir_path, 1) <> "\" Then dir_path = dir_path _
& "\"
old_name = Dir$(dir_path & "*.*", vbNormal)
Do While Len(old_name) > 0
' Rename this file.
new_name = Replace$(old_name, from_str, to_str)
If new_name <> old_name Then
Name dir_path & old_name _
As dir_path & new_name
i = i + 1
End If
' Get the next file.
old_name = Dir$()
Loop
MsgBox "Renamed " & Format$(i) & " files."
Exit Sub
RenameError:
MsgBox Err.Description
End Sub
|
|
|
|
|
|