views:

294

answers:

1

I have created a shared add-in in Visual Studio 2008 and using the shared add-in wizard and am coding in VB. When run the add in in Access 2003 I want to check if the user has a database open, so I set a AccessApplication variable to be the application object in the OnConnection procedure and then on a button click I check if AccessApplication.CurrentDB Is Nothing If there is no database open Access will close correctly after the button is clicked. But if a database is open then I have to stop Access in the VS debugger.

Please find below my OnConnection, OnDisconnection and OnClick procedures any help in this matter would be greatly appreciated.

Public Sub OnDisconnection(ByVal RemoveMode As Extensibility.ext_DisconnectMode, ByRef custom As System.Array) Implements Extensibility.IDTExtensibility2.OnDisconnection
    m_oTestMenu.Delete()
    m_oTestBtn.Delete()

    m_oTestMenu = Nothing
    m_oTestBtn = Nothing

    AccessApplication = Nothing
End Sub

Public Sub OnConnection(ByVal application As Object, ByVal connectMode As Extensibility.ext_ConnectMode, ByVal addInInst As Object, ByRef custom As System.Array) Implements Extensibility.IDTExtensibility2.OnConnection
    Dim oCommandBars As Microsoft.Office.Core.CommandBars

    On Error GoTo ErrHandler

    AccessApplication = CType(application, Microsoft.Office.Interop.Access.Application)

    oCommandBars = AccessApplication.CommandBars

    ' Add the menu to the existing menu list
    m_oTestMenu = AddMenu(oCommandBars, "Test", "Test")

    ' Now create menu options
    m_oTestBtn = AddMenuButton(m_oTestMenu, _
        "TestBtn", MsoButtonStyle.msoButtonIconAndCaption, "Test Btn", MsoButtonState.msoButtonUp)

    ' Clean up
    oCommandBars = Nothing
    Exit Sub

ErrHandler: oCommandBars = Nothing MsgBox("Error") End Sub

Private Sub m_oTestBtn_Click(ByVal Ctrl As Microsoft.Office.Core.CommandBarButton, ByRef CancelDefault As Boolean) Handles m_oTestBtn.Click
    Dim AccessDB As dao.Database

    On Error GoTo ErrHandler

    AccessDB = AccessApplication.CurrentDb

    MsgBox("DB Found " & AccessDB.Name)

    'Try To Close Everything
    AccessDB.Close()
    AccessDB = Nothing

    AccessApplication.CurrentDb.Close()
    AccessApplication = Nothing

    Exit Sub

ErrHandler: MsgBox("Click Error") AccessDB = Nothing End Sub

+1  A: 

Having found this article

http://www.xtremevbtalk.com/showthread.php?t=160433

It appears that I needed to manually garbage collect at the end of my OnDisconnect procedure.

Having added

        GC.Collect()
    GC.WaitForPendingFinalizers()

To the end of the OnDisconnect function Access now closes

Hope this is of help to others