I use the following routine in a form that looks up a 'CloseCount' and 'CompactFrequency' from a settings table. If the close count exceeds the compact frequency then it will compact the datbase when it closes and reset the 'CloseCount' to 1
Have a look at the attached demo file.
To compact on close on demand use the following code
Private Sub cmdCompactNow_Click()
Application.SetOption "Auto Compact", True
DoCmd.Quit
End Sub
reset the Auto Compact to false when the DB opens
Private Sub Form_Open(Cancel As Integer)
Application.SetOption "Auto Compact", False
End Sub
Hope that helps and answers the question.