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

Format cells as time
Select range and press Ctrl+Shift+2 to format cells as time. (Shift 2 is the @ sign).

Jon Peltier

MrExcel MVP
Joined
May 14, 2003
Messages
4,966
Office Version
  1. 365
Platform
  1. Windows
  2. MacOS
Code:
MyFileName = Dir("C:\Test") 
Do while Len(MyFileName) > 0 
  if MyFileName <> "." and MyFileName <> ".." Then
    Msgbox MyFileName 
  End If
  MyFileName = Dir() 
loop
 

VitaminB6

Board Regular
Joined
Oct 11, 2004
Messages
208
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.
 

Jon Peltier

MrExcel MVP
Joined
May 14, 2003
Messages
4,966
Office Version
  1. 365
Platform
  1. Windows
  2. MacOS
Code:
MyFileName = Dir("C:\Test") 
Do while Len(MyFileName) > 0 
  if MyFileName <> "." and MyFileName <> ".." Then 
    Msgbox MyFileName 
    Exit Do
  End If 
  MyFileName = Dir() 
Loop
 

Forum statistics

Threads
1,136,504
Messages
5,676,254
Members
419,616
Latest member
quickflip

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
Top