Determine Drive Types and Next Available Drive Letter

When dealing with drive types and letters it is nice to have a simple function to give you that information. The function shown below will cycle through each of the valid drives on the system running the program and tell you what each type is. Once it is finished, it tells you what the next available drive letter is. In dealing with network applications, it is sometimes necessary to add a drive letter for a new connection.

The first thing you will need is an API declaration. This declaration looks like the following:

Declare Function GetDriveType  Lib "kernel32" Alias "GetDriveTypeA" (ByVal nDrive As String)As Long

The next thing you will need is the function to actually perform the work for you. The function looks like the following:

Function FreeDrive() As String
	Dim DriveNum As String    'To cycle through drive letters in order
	Dim DriveType As Long     'To hold the type of drive it is
	DriveNum = 64             'Prime the variable to be used in the loop
	 Do
	 	DriveNum = DriveNum + 1   ' start at drive zero.
	 	DriveType = GetDriveType(Chr$(DriveNum) & ":")
	 		If DriveType = 1 And DriveNum > 67 Then Exit Do
	 			Select Case DriveType
	 				Case 0: MsgBox Chr$(DriveNum) + ": is An Unknown type"
	 				Case 1: MsgBox Chr$(DriveNum) + ": Does Not Exist"
	 				Case 2: MsgBox Chr$(DriveNum) + ": is a Removable Drive"
	 				Case 3: MsgBox Chr$(DriveNum) + ": is a Fixed Drive"
	 				Case 4: MsgBox Chr$(DriveNum) + ": is a Remote Drive"
	 				Case 5: MsgBox Chr$(DriveNum) + ": is a CD-ROM Drive"
	 				Case 6: MsgBox Chr$(DriveNum) + ": is a RAM Drive"
	 			End Select
	 Loop

	 FreeDrive = Chr$(DriveNum) + ":"  'Return the next available drive letter
	 End Function

Finally, you need to place the code in an event procedure or other routine to call the FreeDrive Function. In this case, we are simply calling the function by placing the return value into a message box.

Sub Click(Source As Button)
	Msgbox "Next Available Drive letter is " & FreeDrive()
End Sub