代码之家  ›  专栏  ›  技术社区  ›  Ans

Excel:循环浏览嵌套文件夹并复制粘贴文件:需要对象错误

  •  0
  • Ans  · 技术社区  · 7 年前

    我正在尝试遍历根文件夹及其子文件夹和子文件夹的子文件夹,并将其文件复制粘贴到某个新位置:

      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 回复  |  直到 5 年前
        1
  •  2
  •   Brian M Stafford    7 年前

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

    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
    
    推荐文章