Question for Dir() to get the file name in a directory

VitaminB6

Board Regular
Joined
Oct 11, 2004
Messages
208
I use the following code to get all the files name in C:\Test and it works.
However, I have one question about this code which is everytime it gets "." first and then ".." , and finally the file names. My question is that is there any way to avoid "." and ".." in the beginning of the loop but the file name?

MyFileName=Dir("C:\Test\")
Do while MyFileName>0
Msgbox MyFileName
MyFileName=Dir()
loop

Thank you
 

Excel Facts

Create a Pivot Table on a Map
If your data has zip codes, postal codes, or city names, select the data and use Insert, 3D Map. (Found to right of chart icons).
Code:
MyFileName = Dir("C:\Test") 
Do while Len(MyFileName) > 0 
  if MyFileName <> "." and MyFileName <> ".." Then
    Msgbox MyFileName 
  End If
  MyFileName = Dir() 
loop
 
Upvote 0
Hi Jon

Thank you for your reply. This is good. However, what I need is just the first file in that folder but need not to go through the whole loop. What I am trying to do is to get the first file name and exit the loop.
 
Upvote 0
Code:
MyFileName = Dir("C:\Test") 
Do while Len(MyFileName) > 0 
  if MyFileName <> "." and MyFileName <> ".." Then 
    Msgbox MyFileName 
    Exit Do
  End If 
  MyFileName = Dir() 
Loop
 
Upvote 0

Forum statistics

Threads
1,214,585
Messages
6,120,399
Members
448,957
Latest member
Hat4Life

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top