У меня это работает.У меня есть класс с именем "DirectoryLooper".Это выполняет Dir для каждой папки отдельно и делает сравнение ранее.Единственный недостаток в этом, который также существует в вашем коде, - это если файлы имеют разное количество файлов.Тогда и ваш код, и мой код прекратят работу, когда папка с меньшим количеством файлов попадет в последний файл.
Private FilePath_ As String
Private fileArray() As String
Private fileIndex As Long
Public Property Let FilePath(ByVal FilePath As String)
FilePath_ = FilePath
End Property
Public Property Get FilePath() As String
FilePath = FilePath_
End Property
Public Property Get NumberFiles() As String
NumberFiles = fileIndex
End Property
Public Sub SetDir()
Dim fileLoop As String
fileIndex = 0
fileLoop = Dir(FilePath_)
Do While fileLoop <> ""
ReDim Preserve fileArray(0 To fileIndex) As String
fileArray(fileIndex) = fileLoop
fileIndex = fileIndex + 1
fileLoop = Dir
Loop
End Sub
Public Function ReturnFile(ndxOfFiles As Long)
ReturnFile = fileArray(ndxOfFiles)
End Function
Затем в главном модуле приведены соответствующие части вашего кода с моими дополнениями.
Sub LoopThroughAllFiles()
Dim wb As Workbook
Dim wb2 As Workbook
Dim dirOne As DirectoryLooper
Dim dirTwo As DirectoryLooper
Dim ndxFiles As Long
Dim ndxCount As Long
Set dirOne = New DirectoryLooper
Set dirTwo = New DirectoryLooper
dirOne.FilePath = "C:\SourceFolder\"
dirTwo.FilePath = "C:\DestinationFolder\"
dirOne.SetDir
dirTwo.SetDir
If dirOne.NumberFiles < dirTwo.NumberFiles Then
ndxCount = dirOne.NumberFiles - 1
Else
ndxCount = dirTwo.NumberFiles - 1
End If
ndxFiles = 0
Do While ndxFiles <= ndxCount
Set wb = Workbooks.Open(Filename:=dirOne.FilePath & dirOne.ReturnFile(ndxFiles))
Set wb2 = Workbooks.Open(Filename:=dirTwo.FilePath & dirTwo.ReturnFile(ndxFiles))
DoEvents
wb.Close SaveChanges:=True
wb2.Close SaveChanges:=True
DoEvents
ndxFiles = ndxFiles + 1
Loop
End Sub