VB code to transfer files from a folder to another folder

hi guys! i need help!
i need a code that will transfer all the files in one folder to another folder.
 
ex:

folder c:\mainfolder contains picture files, and every now and then new pictures will be added to that directory.
its like saying folder mainfolderis the main repository of the picture files.

lets say i have another folder named temp. what i want the code to do is copy all the new files added to the mainfolder or all the files in it and copy it to temp folder overwriting the existing ones. i dont want windows to ask me if i want to overwrite the existing files, i want the code to just copy all the files from the mainfolder.

thanks in advance for the help!
have a nice day!



c0zeeAsked:
Who is Participating?
 
Stephen MandersonConnect With a Mentor Software EngineerCommented:
Hi there, if can use shfileoperation

Option Explicit
Private Declare Function SHFileOperation Lib "shell32.dll" Alias "SHFileOperationA" (lpFileOp As SHFILEOPSTRUCT) As Long
Const FO_COPY = &H2
Const FO_DELETE = &H3
Const FO_MOVE = &H1
Const FO_RENAME = &H4
Const FOF_ALLOWUNDO = &H40
Const FOF_SILENT = &H4
Const FOF_NOCONFIRMATION = &H10
Const FOF_RENAMEONCOLLISION = &H8
Const FOF_NOCONFIRMMKDIR = &H200
Const FOF_FILESONLY = &H80

Private Type SHFILEOPSTRUCT
   hwnd      As Long
   wFunc     As Long
   pFrom     As String
   pTo       As String
   fFlags    As Integer
   fAborted  As Boolean
   hNameMaps As Long
   sProgress As String
End Type

Private Sub cmdcopy_Click()

Dim result As Long, filecopy As SHFILEOPSTRUCT

With filecopy
       .hwnd = Me.hwnd
       .wFunc = FO_COPY
       .pFrom = "c:\mainfolder\*" & vbNullChar & vbNullChar
       .pTo = "c:\otherfolder" & vbNullChar & vbNullChar
       .fFlags = FOF_NOCONFIRMMKDIR
End With
result = SHFileOperation(filecopy)
If result <> 0 Then
       ' Operation failed
       MsgBox Err.LastDllError
End If

End Sub
0
 
gbzhhuConnect With a Mentor Commented:
A simpler way (don't know about which is faster performance wise)

    Dim fso As Scripting.FileSystemObject
    Dim oFolder As Folder
    Dim oFile As File
   
    Set fso = New FileSystemObject
   
    Set oFolder = fso.GetFolder("C:\mainfolder")

    For Each oFile In oFolder.Files
        fso.CopyFile oFile.Path, "C:\temp\" & oFile.Name
        oFile.Delete True
    Next oFile
   
    Set fso = Nothing
    Set oFolder = Nothing
    Set oFile = Nothing
0
 
c0zeeAuthor Commented:
both of them worked fine!
thanks
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.