Link to home
Start Free TrialLog in
Avatar of zimmer9
zimmer9Flag for United States of America

asked on

How to rename a file even if a file by the same name already exists using Access 2003?

I am developing an Access 2003 application..

How would you rewrite the following code to rename a file even if a file with the same name (AGCS_NyCashBreaksBod.txt) already exists:

MyPath = CurrentProject.Path

filedat = "\AGCS_NyCashBreaksBod.dat"

newfiledat = "\AGCS_NyCashBreaksBod.txt"

If Dir(MyPath & filedat) <> "" Then
   Name MyPath & filedat As MyPath & newfiledat
End If
ASKER CERTIFIED SOLUTION
Avatar of mvidas
mvidas
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
try


If Dir(MyPath & filedat) <> "" Then
   if dir(MyPath & newfiledat) <>"" then
      kill MyPath & newfiledat  'delete the file if exists
      end if
   Name MyPath & filedat As MyPath & newfiledat
End If
Try this - you'll need a reference to the MS Scripting runtime library.
Dim fso As New FileSystemObject

MyPath = CurrentProject.Path

filedat = "\AGCS_NyCashBreaksBod.dat"

newfiledat = "\AGCS_NyCashBreaksBod.txt"

fso.CopyFile MyPath & filedat , MyPath & filedat , True

Open in new window

MyPath = CurrentProject.Path

filedat = "\AGCS_NyCashBreaksBod.dat"

newfiledat = "\AGCS_NyCashBreaksBod.txt"

If Dir(MyPath & filedat) <> "" Then
   On Error Resume Next
   Kill MyPath & newfiledat
   On Error Goto 0
   Name MyPath & filedat As MyPath & newfiledat
End If

Jim.
Just an FYI, you'll find that the code I posted is a tad faster because you only do the directory search once rather then twice.

If the file is local, it's not a big difference, but if it's on a network share, the difference is noticeable.

Jim.