Search code examples
vbscriptfile-renamefile-move

Move a file to a new folder after it has been renamed


I require a VBScript that renames a file and then moves it from one folder to another. The script currently renames the file correctly, but I cannot figure out how to move the file to the new folder after the renaming.

Below is the script as it exists.

Option Explicit

Const SAVE_LOCATION = "\\pccit2\Int\PC\Inbox"
Const strPath       = "D:\Files\pak\VP\"
Const StrPrefix     = "VP"

Dim FSO
Dim FLD
Dim fil
Dim strOldName
Dim strNewName

Set FSO = CreateObject("Scripting.FileSystemObject")
Set FLD = FSO.GetFolder(strPath)

For Each fil In FLD.Files
    strOldName = fil.Path
    strNewName = strPath & strPrefix & Right(strOldName, 10)
    FSO.MoveFile strOldName, strNewName
Next

For Each fil In FLD.Files
    If strNewName = 1 Then
        FSO.MoveFile "\\pccit2\Int\PC\Inbox"
    End If
Next

Set FLD = Nothing
Set FSO = Nothing

I have tried a variety ways of getting the file to move. Here are some other attempts:

If FSO.FileExists("D:\Files\pak\VP\*.*") Then
    FSO.MoveFile "D:\Files\pak\VP\*.*", "\\pccit2\Int\PC\Inbox\*.*"
End If

Another attempt

If fil.FileExists("D:\Files\pak\VP\*.*") Then
    fil.MoveFile "D:\Files\pak\VP\*.*" , "\\pccit2\Int\PC\Inbox\*.*"
End If

Solution

  • MoveFile is a method of the FileSystemObject object. It expects at least 2 arguments (source and destination), and wildcards can only be used in the source path, not in the destination path. The destination must be a file or folder path (with a trailing backslash if it's a folder). The respective method of file objects is Move, which can be called with just one argument (the destination path). Also, you can move and rename a file in one step. Just specify the destination path with the new file name.

    For Each fil In FLD.Files
        strNewName = FSO.BuildPath(SAVE_LOCATION, strPrefix & Right(fil.Name, 10))
        fil.Move strNewName
    Next
    

    If you want to separate renaming from moving you can rename the file by simply changing its name:

    For Each fil In FLD.Files
        fil.Name = strPrefix & Right(fil.Name, 10)
        fil.Move SAVE_LOCATION & "\"
    Next