Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
 
TitleNumber the files in a directory
DescriptionThis example shows how to number the files in a directory in Visual Basic 6.
Keywordsrename files, number files
CategoriesFiles and Directories, Utilities
 
When the user selects a directory and clicks Go, the program uses Dir to list the files in the directory. It saves the file's extension and renames the file using a specified prefix and number. For example, you could use this program to rename the files in a directory Test001.txt, Test002.txt, and so forth.

Note that the Dir function returns files in an unpredictable order so the files will probably not have the same alphabetical order. If you need that, load the whole list of files and sort it before processing the names.

 
Private Sub cmdGo_Click()
Dim directory As String
Dim filename As String
Dim filenames As New Collection
Dim prefix As String
Dim i As Integer
Dim Index As Integer
Dim pos As Integer
Dim extension As String
Dim new_name As String
Dim mask As String

    MousePointer = vbHourglass

    mask = txtMask.Text
    directory = Trim$(txtDirectory.Text)
    If Right$(directory, 1) <> "\" Then _
        directory = directory & "\"

    ' Get the file names.
    filename = Dir(directory & "*.*")
    Do While filename <> ""
        filenames.Add filename
        filename = Dir
    Loop
    
    ' Rename the files.
    Index = CInt(txtNumberFrom.Text)
    prefix = Trim$(txtPrefix.Text)
    For i = 1 To filenames.Count
        filename = filenames(i)
        pos = InStr(filename, ".")
        If pos > 0 Then
            extension = Right$(filename, Len(filename) - _
                pos + 1)
        Else
            extension = ""
        End If
        Name directory & filename As _
             directory & prefix & _
                Format$(Index, mask) & extension
        Index = Index + 1
    Next i

    MousePointer = vbDefault
    MsgBox "Moved" & Str$(filenames.Count) & " files."
    File1.Refresh
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated