使用VBA从文件夹和子文件夹复制文件

时间:2019-02-21 14:08:09

标签: excel vba

我需要从文件夹和子文件夹复制文件,但是下面的代码仅搜索主文件夹内的子文件夹。但是子文件夹中也有一些子文件夹 例如:C:\ abc \ bca-因为该abc是主文件夹,而bca是子文件夹,所以代码正在为此工作。 对于c:\ abc \ bca \ cab或c:\ abc \ zxc \ cvg,它在子文件夹的文件夹中不起作用, 请帮我。 在此先感谢

Sub copy_files_from_subfolders()

Dim fso As Object
Dim fld As Object
Dim fsofile As Object
Dim fsofol As Object
Dim filename As String
Dim snumber As Double
snumber = InputBox("Enter the Number", "Message from D")
filename = "_PTA.pdf"
sourcepath = "\\chec.local\"
destinationpath = "R:\Desa"

If Right(sourcepath, 1) <> "\" Then
sourcepath = sourcepath & "\"
End If

Set fso = CreateObject("scripting.filesystemobject")
Set fld = fso.GetFolder(sourcepath)
If fso.FolderExists(fld) Then
    For Each fsofol In fso.GetFolder(sourcepath).SubFolders
        For Each fsofile In fsofol.Files
            If InStr(1, fsofile.Name, snumber) = 1 Then
            MsgBox "Documents Copied"
            fsofile.Copy destinationpath
            End If
        Next
    Next
End If
End Sub

0 个答案:

没有答案