Patrick
Patrick

Reputation: 75

VBA copy paste all files in a folder

My macro is running well since 2 months but now I need some help for another issue. We are running an controller on our server which is sending mails to our customer with attached pdf. Now this controller and my macro are running sometimes at the same time and when my macro is creating pdfs the controller wants to send it but is not able to do so because its already in creation. Now I thought the macro could save pdf into another folder and after that it will copy paste all files into the right folder for sending.

My code is this:

Function Copy()

   Dim MyFile2 As Sting
   Dim myPath2 As String, myPath3 As String

   myPath2 = "L:\Host_Export\Pdf-Kundenmail\Test\"
   myPath3 = "L:\Host_Export\Pdf-Kundenmail\"
   MyFile2 = Dir(myPath2 & "*.*")
   Do
        If MyFile2 = "" Then Exit Do
        FileCopy myPath2 & MyFile2, myPath3 & MyFile2
        End If
        myFile2 = Dir
    Loop

End Function

But if I run it there is an error: error on compilation userdefined typ could not be defined. like this: https://i0.wp.com/www.port135.com/wp-content/uploads/2012/08/error1-1.png. I alredy googled but don't get it how to set up or import something to fix this issue.

Upvotes: 4

Views: 13781

Answers (2)

Preston
Preston

Reputation: 8187

Your code won't work because as @user3598756 said, you spelled string incorrectly. To improve your form though, use a do while loop to combine the if and do statements like so:

Function Copy()
   Dim MyFile2 As String
   Dim myPath2 As String, myPath3 As String

   myPath2 = "L:\Host_Export\Pdf-Kundenmail\Test\"
   myPath3 = "L:\Host_Export\Pdf-Kundenmail\"
   MyFile2 = Dir(myPath2 & "*.*")
   Do while MyFile2 <> ""
        FileCopy myPath2 & MyFile2, myPath3 & MyFile2
        myFile2 = Dir
   Loop
End Function

Upvotes: 4

Harun24hr
Harun24hr

Reputation: 36870

Following sub will copy all files from source folder to destination folder.

    Sub AllFiles()
    Dim FSO As Object
    Dim FromPath As String
    Dim ToPath As String

        FromPath = "C:\Users\Alam\Music\Awlad Hossain"  'Souece Folder
        ToPath = "C:\MyExcelFiles"    'Destination folder

            If Right(FromPath, 1) = "\" Then
                FromPath = Left(FromPath, Len(FromPath) - 1)
            End If

            If Right(ToPath, 1) = "\" Then
                ToPath = Left(ToPath, Len(ToPath) - 1)
            End If

        Set FSO = CreateObject("scripting.filesystemobject")

            If FSO.FolderExists(FromPath) = False Then
                MsgBox FromPath & " doesn't exist"
                Exit Sub
            End If

        FSO.CopyFolder Source:=FromPath, Destination:=ToPath
        MsgBox "You can find the files and subfolders from " & FromPath & " in " & ToPath

    End Sub

More details here:

Upvotes: 1

Related Questions