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

我的macros从2个月开始运行良好,但现在我需要一些帮助来解决另一个问题。 我们正在我们的服务器上运行一个控制器,通过附件pdf向我们的客户发送邮件。 现在这个控制器和我的macros有时在同一时间运行,当我的macros创buildPDF文件时,控制器想要发送它,但是不能这样做,因为它已经在创build。 现在我以为macros可以将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 。 我试着用googlesearch,但不知道如何设置或导入一些东西来解决这个问题。

你的代码不会编译,因为@ user3598756说,你拼错了string。 为了改善你的表单,使用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 

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

  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 

更多细节在这里: