Changing the Name of a File or Folder the Name Function

To rename a file or folder, use the Name function, as follows: Name old_pathname As new_pathname

Old_pathname is the name and path of a file or folder that you want to rename. New_pathname specifies the new name and location of the file or folder. Using the Name function, you can move a file from one folder to another; however, you can't move a folder.

Try this function out in the Immediate window (replace the example names with the actual names of your files). Here are some precautions to consider:

■ The filename in new_pathname may not refer to a file that already exists.

Name "C:\System.1st " As "C:\test.txt"

Because the file C:\test.txt already exists on drive C, Visual Basic displays the following error message: "File already exists." Similarly, the "File not found" error message will appear if the file you want to rename does not exist.

■ If new_pathname already exists, and it's different from old_pathname, the Name function moves the specified file to a new folder and changes its name, if necessary.

Name "C:\System.1st " As "D:\test.txt"

Because the test.txt file doesn't exist in the root directory on drive D, Visual Basic moves the C:\System.1st file to the specified drive; however, it does not rename the file.

■ If new_pathname and old_pathname refer to different directories and both supplied filenames are the same, the Name function moves the specified file to a new location without changing the filename.

Name "D:\test.txt " As "C:\DOS\test.txt"

The above instruction moves the test.txt file to the DOS folder on drive C.

Tip 8-1: You Can't Rename an Open File

You must close the file before renaming it. The name of the file cannot contain the wildcard characters * or ?.

0 0

Post a comment