Access multiple folders simultaneously (VBA)

1793
1
11-08-2011 08:44 PM
NagendraDhakar
New Contributor
Hi,
I have a loop that adds two layers in every step, and both layers are from different folders. That means that the loop involves going through two different folders simultaneously. I know how to loop through one folder but don't know how to do it for multiple folders.

Following is what I want to do:

inputfile1 = Dir(folder1 + "*.shp")
inputfile2 = Dir(folder2+"*.shp")

do while inputfile1 <> ""
  ' Add inputfile1 and inputfile2 to map

  ' go to next files in respective folders
  inputfile1=Dir
  inputfile2=Dir
Loop


Thanks,

Nagendra
0 Kudos
1 Reply
TimWhiteaker
Occasional Contributor II
I would add the files in the two folders into two separate lists, and then iterate through the lists.  Be careful if the number of files in the two folders is not the same.

Sub RunMe()
  Dim folder1 As String
  folder1 = "C:\some_files\"
  Dim folder2 As String
  folder2 = "C:\more_files\"
  
  Dim fileList1 As Collection
  Set fileList1 = GetShapefilesInFolder(folder1)
  Dim fileList2 As Collection
  Set fileList2 = GetShapefilesInFolder(folder2)
  
  Dim i As Long
  Dim count As Long
  If fileList1.count > fileList2.count Then
    count = fileList1.count
  Else
    count = fileList2.count
  End If
  
  For i = 1 To count
    ' Add files to map
    If i <= fileList1.count Then
      Debug.Print "1: " & fileList1.Item(i)
    End If
    If i <= fileList2.count Then
      Debug.Print "2: " & fileList2.Item(i)
    End If
  Next

End Sub

Private Function GetShapefilesInFolder(folder As String) As Collection
  Dim files As New Collection
  
  Dim file As String
  file = Dir(folder & "*.shp")
  Do While file <> ""
    files.Add (file)
    file = Dir
  Loop

  Set GetShapefilesInFolder = files
End Function
0 Kudos