Option Compare Database
Option Explicit
Sub GetFilesInDirectory(Directory As String, Optional ModifiedDate As Date)
On Error GoTo GetFilesInDirectory_Error
Dim MyDatabase As DAO.Database
Dim MyRecordset As DAO.Recordset
Dim MyProperPath As String, MyFileName As String
'Open the destination recordset
Set MyDatabase = CurrentDb
Set MyRecordset = MyDatabase.OpenRecordset("tblFiles")
'Make sure the path is in the right format
If Right(Directory, 1) <> "\" Then
MyProperPath = Directory & "\"
Else
MyProperPath = Directory
End If
'Find the first file in the directory
MyFileName = Dir(MyProperPath)
'Add the record if found and keep calling Dir until not more files
Do While MyFileName <> ""
'Check to see if a Modified date was passed
If ModifiedDate = 0 Or FileDateTime(MyProperPath & MyFileName) > ModifiedDate Then
With MyRecordset
.AddNew
.Fields("Path") = MyProperPath
.Fields("Name") = MyFileName
.Update
End With
End If
MyFileName = Dir
Loop
CleanUp:
MyRecordset.Close
Set MyRecordset = Nothing
Set MyDatabase = Nothing
Exit Sub
GetFilesInDirectory_Error:
Select Case Err.Number
Case 3022 'Duplicate key error
MyRecordset.CancelUpdate
Resume Next
Case Else
Err.Raise Err.Number
'Because I always close the error box before I look at it
Debug.Print Err.Number, Err.Description
Resume CleanUp
End Select
End Sub