Monday, 22 October 2012

How to Copy or Move a File from one Folder to another Folder using Excel VBA Macro

Excel VBA Macro To Copy or Move a File from one location to another location
Sub Copy_One_File()

Dim SourceFilePath As String
Dim TargetFolderPath As String
Dim FSO As Object

Set FSO = CreateObject("Scripting.FileSystemObject")

SourceFile = "C:\Documents and Settings\Administrator\My Documents\SourceFolder\Sample.xlsx"

'File Path Should Specify Exactly With File Extension

TargetFolderPath = "C:\Documents and Settings\Administrator\My Documents\TargetFolder\"

If Right(TargetFolderPath, 1) <> "\" Then
TargetFolderPath = TargetFolderPath & "\"
End If

'Checking the File Existence using FSO Method If FSO.FileExists(SourceFile) = False Then
MsgBox ("Source File Does Not Exist in Path")
End If

'Checking the File Existence using DIR Method
If Dir(SourceFile) = vbNullString Then
MsgBox ("Source File Does Not Exist in Path")
End If

On Error Resume Next

FSO.CopyFile SourceFile, TargetFolderPath
MsgBox "SuccessFull Copied"

'FSO.MoveFile SourceFilePath, TargetPath  'To Move
'MsgBox "SuccessFull Moved"

End Sub

2 comments:

  1. getting an error when i am using fso.movefile

    ReplyDelete
  2. Dear User Please Describe the Error Type or Error Message...

    Suggestion:
    You should declare the source file name with extenesion correctly.
    Then the macro should work absolutely.
    Please ensure that the source file exist in the path.
    Please ensure that the target path exist.

    Regards.,
    TPR

    ReplyDelete

Follow Me by Email

ExcelKingdom-Popular Posts

ExcelKingdom-Random Posts