You've successfully subscribed to Nicholas Workshop
Great! Next, complete checkout for full access to Nicholas Workshop
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info is updated.
Billing info update failed.

Compact and Repair Database In Access Through VBA

Nicholas Wong
Nicholas Wong

Normally, we need to go through bunch of clicks to do one action in MS Access. For example, “Compact and Repair Database”. This function can compact your database and make the file smaller. If you never used this, it may take some time to find it. Try it. LOL.

But here I would like to show you how to program it and open this function by click on a button by VBA. Like the screenshot. To achieve that, you should add a module (so that it is easier to be resused), and add the following codes.

Public Sub CompactDatabase()
	CloseAllForms
    SendKeys "%tdc"
End Sub

Alternatively, you can add a question box to prompt comfirmation from user.

Public Sub CompactDatabaseNoticeable()
	If MsgBox( _
    "Are you sure to compact this database?" & vbNewLine & _
    "There is good to compact the database always with no harm!" & vbNewLine & _
    "But this will restart this analyser.", _
    vbYesNoCancel + vbExclamation) = vbYes Then
        CloseAllForms
        SendKeys "%tdc"
    End If
    End Sub

Also, you need to add a function to close all the forms so that your applications can focus on the main database window and perform the action.

Public Sub CloseAllForms()  
    Dim intIndex As Integer  
    For intIndex = Forms.Count – 1 To 0 Step -1  
        DoCmd.Close acForm, Forms(intIndex).name, acSaveNo  
        Next intIndex  
End Sub  

After all, you can just add the commands to the click event of your button.

Private Sub CompactButton_Click()  
    CompactDatabaseNoticeable  
End Sub  
Unsorted

Nicholas Wong

Fullstack software engineer with strong background in computer science and extensive experience in software engineering and architecture. Studied in NYU, worked in Yahoo, Rakuten and Manulife.