Results 1 to 3 of 3
  1. #1
    Gold Lounger
    Join Date
    Jan 2004
    Location
    Italy
    Posts
    3,245
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Hi have in c:\my_dir\ many file with .mdb extention file.
    I want to loop in dir c:\my_dir\ and delete the last one file oldest base the actual files are presents in dir.
    How to?

    example:
    filea1.mdb created in date 20012010
    fileb2.mdb created in date 21012010

    delete filea1.mdb

    note:
    in dir i can have only 2 file

  2. #2
    Platinum Lounger
    Join Date
    Feb 2002
    Location
    A Magic Forest in Deepest, Darkest Kent
    Posts
    5,681
    Thanks
    0
    Thanked 1 Time in 1 Post
    VBA or script?
    Jerry

  3. #3
    Super Moderator
    Join Date
    Dec 2000
    Location
    New York, NY
    Posts
    2,970
    Thanks
    3
    Thanked 29 Times in 27 Posts
    The following uses FileSystemObject scripting code from within VBA - it should work in any Office app. You need to set a reference to Microsoft Scripting Runtime (scrrun.dll).
    Also note the code takes the liberty of assuming that there will always be exactly two files in the my_dir folder to begin with - if there can be a different number of files at different times, the code would have to be changed to deal with that.

    I'm a little rusty with FSO code, and no doubt there's a quicker way to do this but hey - it appears to work!

    Gary

    Code:
    'Need to set reference to Microsoft Scripting Runtime
    ' (scrrun.dll)
    'This code will only work correctly if there are 2 files in the folder!
    Const FOLDER_PATH As String = "c:\my_dir"
    
    Sub DeleteOldestFileInFolder()
       Dim FSO As New FileSystemObject
       Dim oFolder As Folder
       Dim oFile As File
       Dim oFiles As Files
       Dim oFile1 As File
       Dim oFile2 As File
       Dim i As Long
       Dim FileCreateDate1 As Date
       Dim FileCreateDate2 As Date
       
       Set oFolder = FSO.GetFolder(FOLDER_PATH)
       Set oFiles = oFolder.Files
       i = 1
       For Each oFile In oFiles
          Select Case i
             Case 1
                Set oFile1 = FSO.GetFile(oFile.Path)
             Case 2
                Set oFile2 = FSO.GetFile(oFile.Path)
          End Select
          i = i + 1
       Next 'oFile
       FileCreateDate1 = oFile1.DateCreated
       FileCreateDate2 = oFile2.DateCreated
       'Delete oldest file:
       If FileCreateDate1 < FileCreateDate2 Then
          oFile1.Delete
       ElseIf FileCreateDate1 > FileCreateDate2 Then
          oFile2.Delete
       End If
       Set oFile1 = Nothing
       Set oFile2 = Nothing
       Set oFiles = Nothing
       Set oFolder = Nothing
       Set FSO = Nothing
    End Sub

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •