VBA复制粘贴文件夹中的所有文件

时间:2017-02-08 16:41:13

标签: excel vba

我的宏在2个月后运行良好,但现在我需要一些帮助来解决另一个问题。 我们在我们的服务器上运行一个控制器,它通过附带的pdf向我们的客户发送邮件。现在这个控制器和我的宏有时同时运行,当我的宏创建pdfs时,控制器想要发送它但是由于它已经在创建中而无法这样做。 现在我认为宏可以将pdf保存到另一个文件夹中,之后它会将所有文件粘贴到正确的文件夹中进行发送。

我的代码是:

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

但如果我运行它就会出现错误:error on compilation userdefined typ could not be defined.,如下所示:https://i0.wp.com/www.port135.com/wp-content/uploads/2012/08/error1-1.png。 我用谷歌搜索但是没有知道如何设置或导入一些东西来解决这个问题。

2 个答案:

答案 0 :(得分:2)

您的代码无效,因为@ user3598756说,您拼写错误的字符串。但是要改进表单,请使用do while循环来组合if和do语句,如下所示:

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

答案 1 :(得分:1)

以下子文件会将所有文件从源文件夹复制到目标文件夹。

    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: