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

4
我的宏自2个月以来一直运行良好,但现在我需要帮助解决另一个问题。我们在服务器上运行一个控制器,该控制器向我们的客户发送带有附加PDF的电子邮件。现在,当我的宏创建PDF时,控制器有时会同时运行,但由于PDF已经在创建中,因此无法执行发送操作。
现在我想让宏将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

但是,如果我运行它,就会出现错误:编译错误,无法定义用户定义类型。 就像这样:https://i0.wp.com/www.port135.com/wp-content/uploads/2012/08/error1-1.png。我已经尝试过谷歌搜索,但不知道如何设置或导入某些内容来解决此问题。

你的意思肯定是 myfile2 = dir 吧? - Preston
您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Patrick
2
Dim MyFile2 As Sting 翻译为 Dim MyFile2 As String。使用 Option Explicit 可以避免这种拼写错误。 - user3598756
这是一个非常愚蠢的打字错误,我将设置此选项并更正“Sting”。 - Patrick
2个回答

4

你的代码无法运行,因为如@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

这个更简单,我会用它代替我的代码,谢谢! - Patrick

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

这里有更多详细信息:


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接