The below is compatible with all access database (above code will not work for 2010 database) .The only requirement is add refrence for Microsoft Access:
This code can also make backup before compaction you need to just, pass paramete "True" after Database path.
Code:
Sub test()
Call CompactDatabase("Complete Path of Database")
End Sub
Code:
Public Function CompactDatabase(sDatabasePath As String, Optional BackupBeforeCompactDB As Boolean = False) As Long
'Microsoft Access Library must be added..
Dim strTempFile As String
Dim strPathTemp As String
Dim strExtention As String
Dim strTempF As String
strPathTemp = WorksheetFunction.Substitute(sDatabasePath, ".", "|", Len(sDatabasePath) - Len(Replace(sDatabasePath, ".", "")))
strTempFile = Left(sDatabasePath, InStr(1, strPathTemp, "|") - 1)
strExtention = "." & Right(sDatabasePath, Len(sDatabasePath) - InStr(1, strPathTemp, "|"))
On Error GoTo Err
strTempF = strTempFile & "_Temp" & strExtention
If BackupBeforeCompactDB = True Then
FileCopy sDatabasePath, strTempFile & "_Backup" & strExtention
End If
Application.DisplayAlerts = False
DBEngine.CompactDatabase sDatabasePath, strTempF, dbLangCyrillic
Application.DisplayAlerts = True
FileCopy strTempF, sDatabasePath
Kill strTempF
Exit Function
Err:
CompactDatabase = Err.Number
Err.Clear: Exit Function
End Function
Bookmarks