Renaming and moving Files
Skip Navigation Links.

Renaming and moving Files

Skip Navigation LinksHome :: Visual Basic :: Renaming Files

Here's a simple Visual Basic function you can use in Vb6+/MS Access for renaming and/or moving files.

Also requires: Directory related Constants to be declared in the same module and File Errors Handler

Public Function RenameFile(ByVal OldName As String, NewName As String) As Variant
'A function for renaming and/or moving files
   Dim Msg As String
On Local Error GoTo RenameFile_Err
  
' TO DO check same file format

    RenameFile = False
    
    If FileExists(NewName) = False And Len(NewName) < 256 Then
        If Left(OldName, 1) <> Left(NewName, 1) Then
            Call FileCopy(OldName, NewName) 'different drive
        Else
            Name OldName As NewName 'just move and rename file.
        End If
    Else
    'NEW delete existing file of the same name
        If OldName <> NewName Then 'could be capitalising same name
            If MsgBox("File already exists, do you want to overwrite it?.", vbYesNo + vbCritical) = vbYes Then
                Kill NewName
                If Left(OldName, 1) <> Left(NewName, 1) Then
                    Call FileCopy(OldName, NewName) 'different drive
                Else
                    Name OldName As NewName 'just move and rename file.
                End If
             Else
                Exit Function
            End If
        Else
            Name OldName As NewName 'just rename file.
        End If
    End If

   RenameFile = True

RenameFile_End:
   Exit Function

RenameFile_Err:
    Select Case FileErrors
    Case Is = 0
    ' = OK, Retry ,Yes.
        Resume 0
    Case Is = 1
    ' = Ignore.
        Resume Next
    Case Is = 2
        '= cancel,end
        Resume RenameFile_End
    Case Is = 3
      'other error, not file related
        Msg = "Error #: " & Format$(Err.Number) & vbCrLf
        Msg = Msg & Err.Description
        MsgBox Msg, vbInformation, "RenameFile"
       Resume RenameFile_End
    End Select

End Function

Copy and paste the Visual Basic code below into your module

Please Link to us Next >> Javascript
top of page
all content ©1996/2012 BennySutton.com
all images © their respective owners This site uses Thumbshots previews