我的代码遍历objFile
对象中的每个Folder
:
For Each objFile In objFolder.Files
' do something...
Next objFile
现在我想创建一个内部For Each
循环:
For Each objFile In objFolder.Files
'do something...
For Each objFile In AnotherFolder.Files
'Do something else...
Next objFile
Next objFile
但是,我只能为每个脚本声明一个objFile
。当我尝试运行它时,我收到以下错误:
编译错误:对于已在使用的控制变量
指向内循环的For Each
行。
更新
我尝试使用两个不同的变量,使用以下代码:
For Each objFile In objFolder.Files
' Read creation date of file
Set f = objFSO.GetFile(objFile)
s = f.DateLastModified
Dim objFile2 As Object
ExcelPath = "C:/..."
For Each objFile2 In ExcelPath.Files
If InStr(s, objFile2) Then
objFSO.CopyFile objFile, strNewFolder & "\", True
End If
Next objFile2
Next objFile
然后我收到运行时错误:
运行时错误424:需要对象
再次指向内循环的For Each
行。
如何解决这些问题?
答案 0 :(得分:1)
要检查另一个文件夹中是否存在一个文件夹中的文件,您无需将第一个文件夹中的每个文件与第二个文件夹中的每个文件进行比较。您可以简单地连接路径并使用FileSystemObject.FileExists()
检查文件是否存在。
这样的事情会起作用:
Dim oFile As Object
Dim oFSO As Object
Dim oFolder As Object
Dim folderPath1 As String, folderPath2 As String
folderPath1 = "The\path\of\your\original\folder"
folderPath2 = "The\path\of\your\second\folder"
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder(folderPath1)
For Each oFile In oFolder.Files
If oFSO.FileExists(folderPath2 & "\" & oFile.Name) Then
' File exists in the second folder
End If
Next oFile
编辑:如果由于某种原因必须使用嵌套循环,则可以将上述代码调整为:
Dim oFSO As Object
Dim oFile As Object
Dim oFolder As Object
Dim oFile2 As Object
Dim oFolder2 As Object
Dim folderPath1 As String, folderPath2 As String
folderPath1 = "The\path\of\your\original\folder"
folderPath2 = "The\path\of\your\second\folder"
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder(folderPath1)
Set oFolder2 = oFSO.GetFolder(folderPath2)
For Each oFile In oFolder.Files
For Each oFile2 In oFolder2.Files
' Use oFile.Name and oFile2.Name to do whatever you want.
Next oFile2
Next oFile
希望有所帮助。