Finding Out the Name of the Active Folder the Cur Dir Function

When you work with files, you often need to find out the name of the current folder. You can get this information easily with the CurDir function:


Drive is an optional argument. If you omit drive, VBA uses the current drive.

The CurDir function returns a file path as Variant. To return the path as String, use CurDir$ (where $ is the type declaration character for a string). To get some practice using these functions, let's perform a couple of exercises in the Immediate window:

1. Open a new workbook and switch to Microsoft Visual Basic Editor.

2. Activate the Immediate window and type the following: ?CurDir

When you press Enter, Visual Basic displays the name of the current folder. For example:

If you have a second disk drive (or a CD-ROM drive), you can find out the current folder on drive D, as follows:

If you supply a letter for a drive that does not exist, Visual Basic will display the following error message: "Device unavailable." 3. To store the name of the current disk drive in a variable called myDrive, enter the following:

myDrive = Left(CurDir$,1)

When you press Enter, Visual Basic will store the letter of the current drive in the variable myDrive.

To check the contents of the variable myDrive, type the following and press Enter:


You can modify the above instruction, as follows: myDrive = left(CurDir$,1) & ":"

Visual Basic will return the letter of the drive followed by the colon.

0 0

Post a comment