Learn Microsoft Access Advanced Programming Techniques, Tips and Tricks.

Deleting Folders with DOS Command

We have seen how to create folders with MkDir() DOS Command and learned how to change default folder control to the active database’s parent folder with ChDir() Command.

If we can create a folder then we must be able to remove the folder too.  But, RmDir() Command usage is not as common as the MkDir() Command.  We create new folders or sub-folders to organize files into them so that we can easily locate them when needed.  The removal of those folders become necessary only when need arises for relocation/removal of those files and release the disk space.

We can run RmDir() command directly from the Immediate Window (Debug Window) as shown below, to learn it’s usage:

RmDir "C:\MyFolder"

This command have a safety-check built into it.  When you run the above command it will check whether the folder is totally empty of any sub-folders or files.  If the Command execution was successful then it will not show any message, otherwise it will one of the following two messages:

  1. If the Path specified is not correct then it will show ‘Path Not found’ Error Message.
  2. If the folder is not empty then the message ‘Path/File access error’ is displayed.

Through Windows explorer we can remove a folder with all it’s sub-folders and files in one clean sweep.  If this is done by mistake then we can always restore them from the Recyclebin also, before emptying it.

Network Folders or Files deleted through Windows Explorer are not transferred to Recyclebin.  If you have access rights to delete Network Folders/Files then you must approach the Network Administrator to restore the Folder/File from the latest LAN Backup.  Normally, some users may be allowed to create folders but access rights to delete folder is kept with the Network Administrator, as a safety measure.

Let us write a small function FolderDeletion() to run the RmDir() DOS Command with proper validation checks so that you can add this to your other common functions library.  The function will have the following validation checks before the folder is physically removed:

  1. It checks whether the folder name passed to the function exists, if not displays a message in that effect and aborts the program.
  2. If the folder exists then asks for confirmation from the user to delete the folder.
  3. if the user’s response is not to delete the folder then aborts the program, otherwise attempt to delete the folder.
  4. If the delete action fails then the folder has sub-folders or files in it, abort the program, otherwise delete the folder and show a message.

The VBA Code is given below:

Public Function DeleteFolder(ByVal strFolder As String)
On Error Resume Next

If Len(Dir(strFolder, vbDirectory)) > 0 Then
  'Folder exists, ask for permission to delete the folder
  If (MsgBox("Deleting Folder: '" & strFolder & "', Proceed...?", vbOKCancel + vbDefaultButton2 + vbQuestion, "DeleteFolder()") = vbNo) Then
     'User says not to delete the folder, exit program
     GoTo DeleteFolder_Exit
  Else
     'Delete Folder
     RmDir strFolder
     
     If Err = 75 Then 'folder is not empty, have sub-folders or files
        MsgBox "Folder: '" & strFolder & "' is not empty, cannot be removed."
        GoTo DeleteFolder_Exit
     Else
        MsgBox "Folder: '" & strFolder & "' deleted."
        GoTo DeleteFolder_Exit
     End If
  End If
Else
  MsgBox "Folder: '" & strFolder & "' Not found."
End If

DeleteFolder_Exit:
On Error GoTo 0
End Function

If you want something different to get the same work done then we can use VB Script in Microsoft Access to do that.  VB Script mostly used in Web Pages for Server Side actions.  VB Script uses FileSystemObject to manage Drives, Folders & Files.  We have used it for creating Text, Word and Excel Files before.

You can find those examples in the following links:

First let us write a VB Script Function to create a Folder -  C:\MyProjects.

Public Function FolderCreation(ByVal strFolder As String)
Dim FSysObj, fldr
  
  On Error Resume Next 'arrange to capture the error so that it can be check
  'Create the File System Object
  Set FSysObj = CreateObject("Scripting.FileSystemObject")
  'Call the Create Folder Method of the File System Object with Folder Path as parameter
  Set fldr = FSysObj.CreateFolder(strFolder)
  'if this action ended up with error code 58 then the folder already exists
  If Err = 58 Then
     MsgBox "Folder: '" & strFolder & "' already exists."
     GoTo FolderCreation_Exit
  Else
     MsgBox "Folder: " & strFolder & " created successfully."
  End If
  
FolderCreation_Exit:
On Error GoTo 0
End Function

Copy and paste the above function into the Standard Module of your database.  You can try the function by calling it from the Debug Window with a folder name as shown below:

FolderCreation "C:\MyProjects"

After the sample run, open Windows Explorer and check for the folder name c:\MyProjects. The following VB Script Function FolderDeletion() can be used for removing a folder:

Public Function FolderDeletion(ByVal strFolder As String)
  Dim FSysObj, fldr
  
  On Error Resume Next
  Set FSysObj = CreateObject("Scripting.FileSystemObject")
  Set fldr = FSysObj.GetFolder(strFolder)
  If Err = 76 Then
     MsgBox "Folder: '" & strFolder & "' No found!"
  Else
     If MsgBox("Delete Folder: '" & strFolder & "' Proceed...?", vbOKCancel + vbDefaultButton2 + vbQuestion, "FolderDeletion()") = vbNo Then
         GoTo FolderDeletion_Exit
     Else
         fldr.Delete 'call the Delete Method of the Folder Object
         MsgBox "Folder: '" & strFolder & "' Deleted."
     End If
  End If
FolderDeletion_Exit:
On Error GoTo 0
End Function

Copy and paste the above code into the Standard Module of your database.  You can run the above code either from the Debug Window or call it from a Command Button Click Event Procedure.

Sample Run from Debug Window:

FolderDeletion "C:\MyProjects"

OR

Private Sub cmdRun_Click() FolderDeletion txtFolderPath End Sub

Share:

ChDir and IN Clause of Access Query

Last week we have learned how to change the Directory Path control of VBA to the CurrentProject.Path (active database’s location) with the use of ChDrive() and ChDir() Commands, without altering the Default Database Folder settings under Access Options.

If you don’t like to use DOS commands then you can change the Default Database Folder setting with the following VBA Statement:

Application.SetOption "Default Database Directory", "C:\Developers\Project"

The above statement will change the Default Database Folder to the location specified in the second parameter. The next example changes the Default Database Folder to the active database's location:

Application.SetOption "Default Database Directory", CurrentProject.Path

You can execute the above commands directly in the Debug Window. After executing any of the above commands you may open Access Options from Office Buttons and check the Default Database Folder control value under the Popular options group.

We have already discussed earlier about Updating/Appending data into external Database Tables (external Tables of Access, dBase etc. not linked to the active Access Database)  by using the IN Clause in Queries.  You will find that Article here to refresh your memory.

If you have Queries in your Databases that references Tables in external databases to Update or Append data into them, like the sample SQL given below, it is time to take a relook at them to avoid unexpected side effects.

INSERT INTO Employees (EmployeeID, LastName ) IN 'C:\Developers\Projects\Northwind.mdb' 
SELECT 100221 AS EID, "John" AS LN;

If external or backend database is on a common location on Local Area Network (LAN) Server, serviced by several front-end databases from client machines that itself is asking for separate treatment of the whole issue which we will look at them later, probably next Week. I don't want to mix them up here and confuse you.

Coming back to the IN Clause in the above SQL, if the external database and the current database is on the same Folder then you can omit the lengthy Pathname in the external database reference, like the modified SQL given below:

INSERT INTO Employees (EmployeeID, LastName ) IN 'Northwind.mdb' SELECT 100221 AS EID, "John" AS LN;

The main advantage of writing the IN Clause in this way is that you don't have to change the PathName in all SQLs of Queries on location change of your application. The down side is that you have to ensure that the Default Database Folder location changes to the active database's folder, otherwise the Queries will look for the external database in the old location for updating/appending data.  You can do this, either using the SetOption method or using the ChDir() Command. Both methods are given below for reference:

SetOption Method:

SetOption "Default Database Directory", CurrentProject.Path

This method permanently changes the Default Database Folder control value in the Access Options area and remains intact till it is changed again.  This is a global change to Access Options and may affect other databases when they are open.

ChDir() Method:

Public Function ChangeDir()
Dim vDrive As String * 1, sysPath As String

'get current database Path
  sysPath = CurrentProject.Path

'extract the drive letter alone
'vDrive Variable is dimensioned to hold only one character
  vDrive = sysPath 

'change control to the Drive
  ChDrive vDrive 

'change current location to the database path
  ChDir sysPath 

End Function

This method is harmless because the change is temporary and the Default Database Folder global setting remains intact. You can use the above Code in databases that requires this Function. 

One of these methods must be run immediately on opening the database, either through an Autoexec Macro with the RunCode Action or through the Form_Load() Event Procedure of the first Form opened.

Share:

Microsoft DOS Commands in VBA-2

With the MkDir() Command we were able to create a folder on disk, with the help of a small VBA routine that we have written last week.  We don’t even need a separate program to do this, we can directly execute this command from the Debug Window, like the following example:

MkDir "C:\Developers\Projects"

The only disadvantage of this method is that we cannot perform a validation check before executing this command.  In the VBA program we have included the validation checks.  That program uses constant values as Path, and with few modifications this program can be further improved to accept the Path string as Parameter to the CreateFolder() Function.  The Code with improvements is given below:

Public Function CreateFolder(ByVal folderPath As String)

Dim msgtxt As String, folderName As String

'extract the new Folder Name from the folderPath Parameter
folderName = Right(folderPath, Len(folderPath) - InStrRev(folderPath, "\"))

'check for the new folder name, if not found proceed to create it
If Dir(folderPath, vbDirectory) = "" Then 
   msgtxt = "Create new Folder: " & folderPath & vbCr & "Proceed ...?"
   If MsgBox(msgtxt, vbYesNo + vbDefaultButton1 + vbQuestion, "CreateFolder()") = vbNo Then
      Exit Function
   End If
   MkDir folderPath 'try to create the new folder

'check whether the folder creation was successful or not
   If Dir(folderPath, vbDirectory) = folderName Then
      msgtxt = folderPath & vbCr & "Created successfully."
      MsgBox msgtxt
   Else
'if the code execution enters here then something went wrong
      msgtxt = "Something went wrong," & vbCr & "Folder creation was not successful."
      MsgBox msgtxt
   End If
Else
  'the validation check detected the presence of the folder
   msgtxt = folderPath & vbCr & "Already exists."
   MsgBox msgtxt
End If

End Function

In all the above and earlier examples we have provided the full path of the existing location, where we need the new folder to be created, with the new folder name at the end.  If you are sure where the current location is (or active location of the current database on disk) then you can issue the MkDir() command with the new folder name alone, like the following example:

MkDir "Projects"

As far as VBA is concerned the current location is not what you have selected using the Windows Explorer. Or the one you have selected using DOS Command ChDir() run directly under the DOS Command Prompt.

But, with a small trick we can find out which is the current folder that VBA is aware of, that is by running the Shell() command directly from the Debug Window to invoke the DOS Command Prompt from VBA, like the example given below:

Call Shell("cmd.exe")

The above command will open the DOS Command Prompt (if it is minimized on the task bar then click on it to make that window current), the Cursor will be positioned in the current folder. Check the sample image given below:

If you have used MkDir "Projects" like command without knowing where it is going to be created then type Dir and press Enter Key to display a list of files and directory names with the label <Dir> to indicate they are folders.

That doesn’t mean that the above method is the only option to check the Default Database Folder location.  Select Access Options from Office Button and select the Popular Option Group(Access2007) and you can see the Default Database Folder settings there.  Check the image given below:

Try to open a database from some other location on disk, but this setting will not change and the Default Database Folder will remain active as per this setting.  Without touching the above Access default setting we can change the active folder to the newly opened database’s parent directory with the use of the following DOS Commands from VBA (you can try this by typing these commands directly on the Debug Window):

? CurrentProject.Path

This is not DOS Command, but the above VBA statement retrieves the active database's Path. Let us assume that the retrieved location of the current database is: C:\MDBS

Using the above information in the next two DOS Commands we can change the control to the active database's location, without changing the Default Database Path setting, we have seen earlier:

ChDrive "C" 'change control to C: Drive. This is necessary if control was on a different drive ChDir CurrentProject.Path 'change control to the active database's folder

By combining the above statements we can write a very useful Function ChangeDir() to change the control to the current Database Folder.  Copy and Paste the following Code into a Standard Module of your Database and save it:

Public Function ChangeDir()
Dim vDrive As String * 1, sysPath As String

'get current database Path
  sysPath = CurrentProject.Path

'extract the drive letter alone
'vDrive Variable is dimensioned to hold only one character
  vDrive = sysPath 

'change control to the Drive
  ChDrive vDrive 

'change current location to the database folder
  ChDir sysPath 

End Function

Call the above Function from an Autoexec macro with the RunCode Action or from the Form_Load() Event Procedure of the first Form open (like the Startup Screen or Main Switchboard) to change control to the active database folder.

Share:

Translate



PageRank
Your email address:

Delivered by FeedBurner

Search

Infolinks Text Ads


Blogs Directory

Popular Posts

Search This Blog

Blog Archive

Powered by Blogger.

Labels

Forms How Tos Functions MS-Access Security Reports msaccess forms Animations msaccess animation Utilities msaccess controls Access and Internet MS-Access Scurity MS-Access and Internet Queries External Links msaccess reports msaccess tips Menus and Toolbars Accesstips MsaccessLinks Process Controls Art Work Downloads msaccess How Tos Graph Charts msaccessQuery List Boxes Command Buttons Emails and Alerts Query Combo Boxes Custom Wizards DOS Commands ms-access functions msaccess functions msaccess graphs msaccess reporttricks msaccessprocess security advanced Access Security Array Custom Functions Data Macros Menus Property Report Top Values VBA msaccess email msaccess menus progressmeter Access2007 Auto-Number Command Button Copy Form Join Microsoft Numbering System Records Security Split SubForm Table Utility Variables Workgroup database msaccess wizards Access2003 Accounting Year Action Animation Attachment Binary Numbers Bookmarks Budgeting Calculation ChDir Color Palette Conditional Formatting Controls Data Filtering Data Type Defining Pages Diagram Disk Dynamic Lookup Error Handler Excel Export Expression External Field Type Fields Filter Form Instances Formatting Groups Hexadecimal Numbers Import Labels List Logo Macro Mail Merge Main Form Memo Methods Monitoring Object Reference Objects Octal Numbers Operating System Paste Primary-Key Product Rank Reading Recordset Rich Text Sequence SetFocus Summary Tab-Page Tables Time Difference Union Query User Users Water-Mark Word automatically commands function hyperlinks iSeries Date iif ms-access msaccess msaccess alerts pdf files reference restore switch text toolbar tutorial updating upload vba code

Featured Post

Function Parameter Array Passing

Last week we have explored the usage of ByVal (By Value) and ByRef (By Reference),  in the Function Parameter, to pass the value from  a Va...

Labels

Blog Archive

Recent Posts