How to Use the Dir Function in VBA

104 9
    • 1). Open Microsoft Word.

    • 2). Click "Tools," "Macro" and then "Visual Basic" to open the VBA programming environment.

    • 3). Click "Insert" and "Module."

    • 4). This VBA code gives an example of how to use the Dir function to request all files located in one directory, the C: drive. The procedure saves the individual file names in the "AllFiles" variable and then displays this in a message box for the user. Type or paste the following code block in the Module window:

      Sub ShowFiles()

      Dim NextFile As String

      Dim AllFiles As String

      AllFiles = ""

      NextFile = Dir("C:\", 0)

      While NextFile <> ""

      AllFiles = AllFiles & Chr(13) & NextFile

      NextFile = Dir

      Wend

      MsgBox AllFiles

      End Sub

    • 5). Click "File" and then "Save" to save your work.

    • 6). Press "F5" on your keyboard to run the program. You should see a message box with a list of file names on your C: drive.

Source...
Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.