Excel:遍历嵌套文件夹并复制粘贴文件:对象必填错误

时间:2018-10-15 11:07:11

标签: excel vba excel-vba

我试图遍历根文件夹及其子文件夹以及子文件夹的子文件夹,然后将其文件复制粘贴到新位置:

  Sub Main()
    Dim source As String
    Dim destination As String
    source = ThisWorkbook.Worksheets(1).Cells(1, 2).Value
    destination = ThisWorkbook.Worksheets(1).Cells(2, 2).Value

    'copy files in root folder
    Call DoFolder(source, destination)

    'loop through nested folders
    Dim FileSystem As Object
    Set FileSystem = CreateObject("Scripting.FileSystemObject")

    Dim subFolder As Variant
    subFolder = FileSystem.GetFolder(source)

    'Dim subFolder As Variant
    For Each subFolder In subFolder.SubFolders
        MsgBox (subFolder.Name)
        Debug.Print subFolder.Name

        Call DoFolder(subFolder.Name, destination)
    Next


End Sub

Sub DoFolder(source As String, destination As String)

    'copy files in root folder
    Call Copy(source, destination)

End Sub

Sub Copy(source As String, destination As String)
   Dim fileObject As String
   fileObject = Dir(source & "*.*")
   Do While fileObject <> ""
        FileCopy source & fileObject, destination & fileObject
        fileObject = Dir
    Loop

    MsgBox ("DONE")
End Sub

但是我在object required子项中遇到Main错误。我该如何解决?

1 个答案:

答案 0 :(得分:2)

我总是将变量声明为期望的类型。在这种情况下,它也可以解决您的问题。尝试以下代码:

Dim fso As FileSystemObject
Set fso = New FileSystemObject

Dim subFolder As Folder
Set subFolder = fso.GetFolder(source)

For Each subFolder In subFolder.SubFolders
   MsgBox subFolder.Name
Next