The Daily Newbie - Using the Dir() Function
Explains the basics of using the Dir() command to get file and folder information.
Original Author: Matt Roberts
Code
Depending on the paramters set, To get a file name from a To get a read-only file name from a directory: strFile = Dir ("c:MyFolder*.txt", To get a sub-directory from a directory: strFile = Dir ("c:MyFolder*", To get the label of a drive: strFile = Dir ("d:", Today's copy and paste code lists
To Start
Things Off Right
Today's
Topic:
Using the Dir
Command
Name
Derived From
"Directory"
Used
For:
Getting Information about a
particular folder or file.
VB Help
File Description
Returns a String representing
the name of a file, directory, or folder that matches a specified pattern
or file attribute, or the volume label of a drive. Syntax
Plain
English Description
returns:
patten (*.txt)
Usage:
directory: strFile = Dir
("c:MyFolder*.txt")
vbReadOnly)
vbDirectory)
vbVolume)
Parameters:
values: vbNormal (default), vbReadOnly, vbHidden, VbSystem,
vbVolume, vbDirectory
Copy
& Paste Code:
all of the files in a directory to the debug window. For details on usage
of the Dir ()command in this example, see the Notes below.
Dim strPathAndPattern As String
Dim strFileName As String
strPathAndPattern = InputBox("Enter a path and search pattern (ex: c:windows*.exe):")
strFileName = Dir(strPathAndPattern)
Debug.Print strFileName
While strFileName > ""
strFileName = Dir
Debug.Print strFileName
Wend
Notes
files, you must do a "two step" proccess. In the example above, notice
that the first time Dir() is called (before the While...Wend loop), the
parameter strPathAndPatten is used. After that, the call is
simply Dir. (strFileName = Dir). This is sort of confusing if
you don't know what is going on. When I first used the Dir command, I
kept getting the same file name over and over. This is because using
Dir() with a path parameter will always return the FIRST match. To
get subsequent matches, you simply call Dir(). It remembers the last
pattern and passes the NEXT match. Really screwy.
exists:
If Dir
("c:MyFolderlog.txt") > ""
Then
MsgBox "File Already
Exists!"
End
If
This is because Dir() will return an empty string ("") if
a match is not found, but will return the file name if a match
is found.
this is a little different. Because of the way Windows handles folder
names, there is always a folder named "." and another named ".." . As
odd as that seems, these names represent the current folder and the
parent folder. So to find out if a certain folder exists, you can do
this:
If Dir ("c:windowssystem",
vbDirectory) > ".." Then
MsgBox "Folder
Already Exists!"
End If
Click Here
Loading Comments ...
Comments
No comments have been added for this post.
You must be logged in to make a comment.