See Also Example
Changes the name of a disk file or directory.
Name oldfilespec As newfilespec
The Name statement is similar to the operating system RENAME command, but Name can also be used to change the name of a directory. Using Name, you can move a file from one directory to another, but you can't move a directory.
The arguments oldfilespec and newfilespec are string expressions If the path in newfilespec exists and is different from the path in oldfilespec, the Name statement moves the file to the new directory and renames the file if necessary. If newfilespec and oldfilespec have different paths and the same file name, Name moves the file to the new directory and leaves the file name unchanged., each of which contains a file name and an optional path.
The file specified by oldfilespec must exist and the file specified by newfilespec cannot already exist. Both newfilespec and oldfilespec must be on the same drive.
Using Name on a file currently open by Visual Basic produces an error. You must close an open file before renaming it.
Name Statement Example
The example moves a file from one directory to another and renames it at the same time. To try this example, paste the code into the Declarations section of a form. Then press F5 and click the form.
Sub Form_Click ()
Dim FName1, FName2, Msg, NL, TestDir ' Declare variables.
NL = Chr(10) ' Define newline.
FName1 = "NMSTMTX.DAT" ' Define filenames.
FName2 = "NMSTMTY.DAT"
TestDir = "\TEST.DIR" ' Test directory name.
Open FName1 For Output As #1 ' Create a test file.
Print #1, "test data" ' Put something in file.
MkDir TestDir ' Make test directory.
Name FName1 As TestDir & "\" & FName2 ' Move and rename.
Msg = "A new file, " & FName1 & " has been created "
Msg = Msg & "in " & CurDir$ & ". Once created, it was "
Msg = Msg & "moved to " & TestDir & " and renamed "
Msg = Msg & FName2 & "." & NL & NL
Msg = Msg & "Choose OK to remove the test data file and "
Msg = Msg & "directory."
MsgBox Msg ' Display message.
Kill TestDir & "\" & FName2 ' Remove file from disk.
RmDir TestDir ' Remove test directory.