Jose,
This cannot be done properly through code. The reason is, Access cannot
compact an open database; when you run Compact and Repair from the menu,
Access closes the database first, and then compacts the closed file and
re-opens it at the end. Obviously, you can;t have code running off a
closed database!
I said "properly" because you could use DoMenuItem to do it, but it's
not advisable; for one thing, it will not be easy to get back to the
exact point where you were (open forms/reports and criteria for them,
selected records etc.), plus it doesn't look good for the user. I can't
think of any other drawback right now, all suggestions welcome!
Since you mention you want to compact the current database, I presume
this is a monolithic database (as opposed to a front-end / back-end
split design). In this case, and assuming you Access version is 2000 or
newer, your other option is to activate the Compact On Close option
(Tools > Options, tab General) so your database is compacted every time
you close it. This should be sufficient in most cases. Note: this
setting is database-specific, it will not apply on all your databases.
HTH,
Nikos