MS Access – VBA – Rename a File

Ever simply needed to rename a file? Well, once again there are a multitude of ways to accomplish this within MS Access. I have seen numerous postings suggest using a scripting object and then copy the file while renaming the copied version. To me, if all you need is to rename the file, this is a uselessly complicated method. Instead why not simply use the Name function? It can all be accomplished in one clean line of code!!!

Name "C:\OldFileName" AS "C:\NewFileName"

Actually, you can even use the Name command to move and rename a file simultaneously.

Name "C:\OldDir\OldFileName" AS "C:\NewDir\NewFileName"

As you can see this is another versatile command to be aware of.

View ratings
Rate this article

5 responses on “MS Access – VBA – Rename a File

  1. Carl Sweetland

    Hi,

    I’ve used this method in the past, but it is now failing.

    My line of code looks like this:
    Name sOldFile As sNewFile

    I get the following error:
    Run-Time error ’5′:
    Invalid procedure call or argument

    When I hover over Name it states “Microsoft Access”

    Do you need a reference for this function?

    1. admin Post author

      What vesion of Access are you running. Name is a built-in statement and should not require any extra references to work.
      There is one notable limitation: “it can only rename an existing directory or folder when both OldPathName and NewPathName are located on the same drive”.

  2. TCheck

    I have directories and files with spaces in them, how would i rename these? When I do try Name “C:\Old Dir\OldFileName” As “C:\New Dir\NewFileName” it tells me it can not find the file, I take out the spaces and it works great.

    1. admin Post author

      Not too sure what to tell you. I did a few tests and they all worked for me just fine.

      Name “C:\Users\Daniel\Documents\My test dir\My Test2.txt” AS “C:\Users\Daniel\Documents\My test dir\My Test.txt”
      Name “C:\Users\Daniel\Documents\My test dir” AS “C:\Users\Daniel\Documents\My test dir2″

      I saw no diffirence whether or not there were, or were not any spaces.

      The only thing I can possibly see is your example does not include the extension of the file, perhaps it was an oversight in the post, but worth checking.

      Name “C:\Old Dir\OldFileName.ext” As “C:\New Dir\NewFileName.ext”

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>