1

I have used a form of the following code successfully many times to open multiple files in a folder and I understand how dir helps set the file path before the while loop, but don't quite understand how call the dir method again with no arguments right before the end of the while loop looks up the next file in the folder:

Sub OpenFiles()

Dim MyFolder As String
Dim MyFile As String

MyFolder = "C:\newFolder"
MyFile = Dir(MyFolder & "\*.xlsx")

Do While MyFile <> ""
Workbooks.Open Filename:=MyFolder & "\" & MyFile

MyFile = Dir

Loop
End Sub

When calling Dir on a string that already has been set with a value, is Dir designed to look to the next file in the list of files at that same path?

2
  • 2
    the MyFile = Dir line is used to get the next entry (i.e. your next file). See this: exceltrick.com/formulas_macros/vba-dir-function Commented Jan 29, 2015 at 20:21
  • 1
    Thanks Alex, good article. I like that it starts it off by noting that Dir is a "very special" function, and it seems to me it was specifically designed anticipating the need to iterate through multiple files in a location and hence designed to be called with no argument later. Commented Jan 29, 2015 at 20:36

1 Answer 1

3

The Dir functions declares a Static variables and uses them for later invocations.

I would guess that the logic is:

  1. Declare index_of_file and number_of_files as static integers

  2. If a parameter is supplied, scan the directory set index_of_file to 1, set number_of_files to the number of files in the folder, and return the first file.

  3. If a parameter is not supplied, increment index_of_file and return the file with that index, or return "" if index_of_file>number_of_files

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.