kwokv616
12-08-2008, 01:07 AM
If I want to compact and repair the current database, I write:
Sub CompactAndRepairDatabase()
CommandBars("Menu Bar").Controls("Tools").Controls("Database utilities").Controls("Compact and repair database...").accDoDefaultAction
End Sub
But what if I want to compact and repair another database while running a code in the current database, how can it be done? or is it possible?
Thanksss!!
This code works by compacting to a temp mdb file and then copying the temp file back to the original file, replacing it. To use it, you'll probably need to add a couple of references:
'Micosoft Jet and replication library
'Windows Scripting Host Object Model
Private Sub compactTheDb(ByVal strPathToDb as string)
Dim fso As New IWshRuntimeLibrary.FileSystemObject
Dim pathToContainingFolder As String
If Not fso.FileExists(strPathToDB) Then Exit Sub
pathToContainingFolder = fso.GetFile(strPathToDB).ParentFolder.path
'Compact to the following destination
Dim pathToDestDB As String
pathToDestDB = Replace(strPathToDB, ".mdb", "-Compacted.mdb")
If fso.FileExists(pathToDestDB) Then fso.DeleteFile (pathToDestDB)
Dim JRO As New JRO.JetEngine
Dim DBEngine As New DAO.DBEngine
Dim DB As DAO.Database
Set DB = DBEngine.OpenDatabase(strPathToDB)
DB.Close
'To compact, specify the connection to the source db, and the connection to the destination db
Dim cnStringDest As String
cnStringDest = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source= " & pathToDestDB & ";Jet OLEDB:Engine Type=5"
Call JRO.CompactDatabase(strCn, cnStringDest)
fso.CopyFile pathToDestDB, strPathToDB 'overwrites the swelled db with the compact db
End Sub
The above code uses a jet 4.0 connection string - won't work with Access 2007 - unless perhaps you modify the connection string.
dfenton
12-12-2008, 03:00 PM
It is completely senseless to recommend JRO, because DAO provides the exact same compact functionality without requiring an additional reference (or late binding). JRO only exists because of the wrong-headed move by MS to push Access developers to use ADO everywhere, even when their data was stored in Jet databases. If you're using Access, JRO is something you should never have any cause to use (with one exception -- if you're doing replication and not using the TSI Synchronizer, it allows you to launch an indirect or Internet synch, while DAO supports only direct) -- it is only useful to those using Jet MDBs from outside Access.