Excel:循环浏览嵌套文件夹并复制粘贴文件:需要对象错误
我正在尝试循环浏览根文件夹及其子文件夹,以及子文件夹的子文件夹,并将其文件复制粘贴到某个新位置:Excel:循环浏览嵌套文件夹并复制粘贴文件:需要对象错误,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 f
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
Sub-Main()
将源设置为字符串
将目标设置为字符串
source=此工作簿。工作表(1)。单元格(1,2)。值
destination=此工作簿。工作表(1)。单元格(2,2)。值
'复制根文件夹中的文件
调用文件夹(源、目标)
'循环浏览嵌套文件夹
将文件系统作为对象
设置FileSystem=CreateObject(“Scripting.FileSystemObject”)
变暗子文件夹作为变量
子文件夹=FileSystem.GetFolder(源)
'将子文件夹变暗为变量
对于subFolder.SubFolders中的每个子文件夹
MsgBox(子文件夹名称)
调试.打印子文件夹.名称
调用DoFolder(subFolder.Name,destination)
下一个
端接头
子文件夹(源为字符串,目标为字符串)
'复制根文件夹中的文件
呼叫副本(源、目标)
端接头
子副本(源作为字符串,目标作为字符串)
将fileObject设置为字符串
fileObject=Dir(源&“***”)
当文件对象“”时执行此操作
文件复制源和文件对象、目标和文件对象
fileObject=Dir
环
MsgBox(“完成”)
端接头
但是,我在
Main
sub中得到了一个objectrequired
错误。如何修复它?我总是将变量声明为预期类型。在这种情况下,它也解决了您的问题。请尝试以下代码:
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
我总是将变量声明为预期类型。在这种情况下,它也解决了您的问题。请尝试以下代码:
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
请注意,您必须添加对Microsoft脚本运行时的引用。谢谢!我已经弄明白了-这是关于
Set
关键字-添加集合,没有错误。请注意,您必须添加对Microsoft脚本运行时的引用。谢谢!我已经弄明白了-这是关于Set
关键字的-添加Set,没有错误。