Tuesday, March 18, 2014

How to iterate over the files in a folder (VBA-Excel)

On our example below, we iterate over all text files (*.txt) inside the folder called "myfolder", please change the path according your folder and if you want to see all the files instead of just the files with a specific extension write just: "*" instead of "*.txt"

Sub over_files()

Dim file As String
Dim folderpath As String
Dim filename As String
Dim Count_files As Integer

''''''Data'''''''''''''''''''''
folderpath = "C:\Users\Guest\Desktop\myfolder\*.txt"
'''''''''''''''''''''''''''''''''''''

   file = Dir(folderpath)
  
Count_files = 0

While (file <> "")

    If Len(file) > 0 Then
    filename = Left(file, Len(file) - 4)
    Count_files = Count_files + 1
    End If
  
   ' your code here

     file = Dir

Wend

End Sub



No comments: