• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 200
  • Last Modified:

Rename a file on HD

How do you rename a file on the HD in Visual Basic?
1 Solution
I've had this snippet for a while and am unsure to whom the auther is, but it works really well.

Option Explicit

Private Sub Form_Load()

   RenameFiles "d:\bat"

End Sub

Private Function GiveNewName%(ByVal Oldname$, ByVal NewName$)

   On Error GoTo Error_In_Renaming

   ' Now rename the file
   Name Oldname$ As NewName$

   ' Return True to indicate a success
   GiveNewName% = True

   Exit Function


   ' Return False to indicate failure
   MsgBox Error$(Err)
   GiveNewName% = False
   Resume Exit_The_Function

End Function

Private Sub RenameFiles(Path$)

Dim t$      ' To hold the filename while renaming
Dim ok%     ' To hold the return values from GiveNewName% and MsgBox
Dim Counter%   ' Counts the files

   ' Get the first filename
   t$ = Dir$(Path$ & "\*.*")
   ' Keep on renaming until the directory contains no unrenamed files
   Do While t$ <> ""

      ' Increment the counter
      Counter% = Counter% + 1
      ' Give new filename that will look like this "FILE####.$$$" where "####" is the Counter%
      ' value and the "$$$" is the original file's extension
      ok% = GiveNewName%(Path$ & "\" & t$, Path$ & "\FILE" & CStr(Counter%) & Right$(t$, 4))

      ' If there was an error renaming the file...
      If Not ok% Then
         ' Ask the user to proceed or quit
         ok% = MsgBox("There was an error renaming " & t$ & " to " & "File" & CStr(Counter%) & Right$(t$, 4) & Chr$(13) & Chr$(13) & "Proceed?", 4 + 32, "Rename files")
         If ok% = 7 Then   ' No was selected
            ' Quit
         End If
      End If

      ' Get new filename
      t$ = Dir$


End Sub

What your looking for is the 'Name' statement. There are three ways it can be used:

Rename a file:
Name "c:\abc.txt" As "c:\xyz.txt"

Rename and move a file:
Name "c:\abc.txt" As "c:\my documents\xyz.txt"

Move a file
Name "c:\abc.txt" As "c:\my documents\abc.txt"
so simple

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now