Multiple Apps

File System Object Move a File to another location

Ease of Use

Easy

Version tested with

2000, 2002, 2003 

Submitted by:

MOS MASTER

Description:

This function will move a file from location a to location b. the optional parameter let's you overwrite a existing file if it exists. 

Discussion:

You need to move files to another location. FSO helps you with that. 

Code:

instructions for use

			

Option Explicit Sub MoveMyFile() Dim sSource As String Dim sDestination As String ' \\ build paths..change to your FileName ' \\ The path of the source document sSource = ThisDocument.Path & "\Test.doc" ' \\ The path of the destination document sDestination = ThisDocument.Path & "\Test\Test Moved.doc" ' \\ Call function to move file Call FSOMoveFile(sSource, sDestination, False) End Sub ' \\ This function moves a file from it's source location to the ' \\ destination location. If bOverwrite is true a exesting file ' \\ in source location is overwritten Public Sub FSOMoveFile(sSource As String, _ sDestination As String, _ bOverwrite As Boolean) Dim FSO As Object On Error GoTo Oops Set FSO = CreateObject("Scripting.FileSystemObject") ' \\ Check if Source file exists if not exit sub If Not fFileExists(FSO, sSource) Then MsgBox "Source file: " & sSource & " doesn't exist", vbCritical GoTo ExitOops End If ' \\ Check if Destiantion file exists if so exit sub If fFileExists(FSO, sDestination) And bOverwrite Then ' \\ Delete existing destination file first and then move the file With FSO .DeleteFile (sDestination) .MoveFile sSource, sDestination End With ElseIf fFileExists(FSO, sDestination) And Not bOverwrite Then ' \\ Not allowed to overwrite existing file so exit GoTo ExitOops Else ' \\ If source file exists and Destination file doesn't ' \\ This will move the document to the new location. FSO.MoveFile sSource, sDestination End If ' \\ Clean Up ExitOops: Set FSO = Nothing Exit Sub Oops: MsgBox "Error # " & Str(Err.Number) & " " & Err.Description Resume ExitOops End Sub ' \\ Function to check if file exists Public Function fFileExists(FSO As Object, sPath As String) If FSO.FileExists(sPath) Then fFileExists = True End Function

How to use:

  1. Open your document.
  2. Press Alt + F11 to open VBE.
  3. Insert-Module. (Insert -> module)
  4. Paste the code there in the window at right. (F7)
  5. Close VBE (Alt + Q or press the X in the top right hand corner).
  6. Save the file.
 

Test the code:

  1. press Alt + F8 to open the macro dialog box.
  2. Select MoveMyFile
  3. Click Run.
 

Sample File:

Move file.zip 20.32KB 

Approved by mdmackillop


This entry has been viewed 100 times.

Please read our Legal Information and Privacy Policy
Copyright @2004 - 2020 VBA Express