Author: Tomas Rutkauskas
Using D6 Pro, Access XP and Jet 4.0 Sp6 - how can I compact Access files?
Answer:
This does it:
1 2 procedure TMainForm.ActionCompactAccessDBExecute(Sender: TObject);
3 var4 JetEngine: Variant;
5 TempName: string;
6 aAccess: string;
7 stAccessDB: string;
8 SaveCursor: TCursor;
9 begin10 stAccessDB := 'Provider = Microsoft.Jet.OLEDB.4.0;' +
11 'Data Source = %s;Jet OLEDB: Engine type = ';
12 stAccessDB := stAccessDB + '5'; {5 for Access 2000 and 4 for Access 97}13 OpenDialog1.InitialDir := oSoftConfig.ApplicationPath + 'Data\';
14 OpenDialog1.Filter := 'MS Access (r) (*.mdb)|*.mdb';
15 if OpenDialog1.execute and (uppercase(ExtractFileExt
16 (OpenDialog1.FileName)) = '.MDB') then17 begin18 if MessageDlg('This process can take several minutes. Please wait till the end
19 '+
20 #13 + #10 + 'of it. Do you want to proceed? Press No to exit.', mtInformation,
21 [mbYes, mbNo], 0) = mrNo then22 exit;
23 SaveCursor := screen.cursor;
24 screen.cursor := crHourGlass;
25 aAccess := OpenDialog1.FileName;
26 TempName := ChangeFileExt(aAccess, '.$$$');
27 DeleteFile(PChar(TempName));
28 JetEngine := CreateOleObject('JRO.JetEngine');
29 try30 JetEngine.CompactDatabase(Format(stAccessDB, [aAccess]),
31 Format(stAccessDB, [TempName]));
32 DeleteFile(PChar(aAccess));
33 RenameFile(TempName, aAccess);
34 finally35 JetEngine := Unassigned;
36 screen.cursor := SaveCursor;
37 end;
38 end;
39 end;
Important Notes:
Include the JRO_TLB unit in your uses clause.
Nobody should use or open the database during compacting.
If the compiler gives you an error on the JRO_TLB unit follow these steps:
Using the Delphi IDE go to Project – Import Type Library.
Scroll down until you reach “Microsoft Jet and Replication Objects 2.1 Library”.
Click on Install button.
Recompile a gain.