Home » excel » vba – How to close an add-in when there are no more References to it?

vba – How to close an add-in when there are no more References to it?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m writing a simple set of modular add-ins in Excel VBA.

In Addin1.xlam, I have selected “Tools.. References” and added MyMenus.xlam as a reference.

Addin1 also has some code to close itself from a menu. But when Addin1 closes, MyMenus stays open, even though it is no longer needed or referenced by anything.

I may also have Addin2 or Addin3 with a reference to MyMenus.

How can I get MyMenus to automatically close when no other open Project has a Reference to it?

Alternatively, how can I tell Addin1 to “close, and also close anything I had a Reference to”?

How to&Answers:

Is keeping the MyMenus add-in open causing any issue? References like this would normally be left open exactly for the reason you describe, i.e. in case it is referenced elsewhere. I would recommend leaving it all as is but if you do want to proceed then it needs to be done in two steps: First remove the reference from the first add-in (Addin1.xlam), and then close the second add-in (MyMenus.xlam). Something like this should work:

Dim objRef As Reference

Set objRef = ThisWorkbook.VBProject.References("MyMenus")

Call ThisWorkbook.VBProject.References.Remove(objRef)

'Do not raise an exception as may not be able to close if the add-in is referenced elsewhere
On Error Resume Next
Call Workbooks("MyMenus.xlam").Close(False)
On Error Goto 0

Note, I have the Microsoft Visual Basic for Applications Extensibility reference added to the project (alternatively just declare objRef as a Variant).

When you do finally then close AddIn1.xlam, make sure you do so without saving otherwise you’ll permanently lose the reference.

Answer:

I solved this in a different way because the users were constantly saving the sheet and destroying the reference. It’s a bit of a hack but what in Excel VBA isn’t?

Public Sub CloseYourself()
    Application.OnTime Now + TimeValue("00:00:00"), "CloseYourselfNow"
End Sub

Private Sub CloseYourselfNow()
    On Error Resume Next
    ThisWorkbook.Close False
End Sub

Basically, you call CloseYourself in the Workbook_BeforeClose event, which schedules CloseYourselfNow for 0 seconds from now (this part of Excel is single threaded so it waits for the original workbook to close). By the time CloseYourselfNow runs, the reference will have been removed and the addin can close itself. You need the On Error Resume Next in case other still workbooks have a reference. Finally, you can change the False to some check that is only true on your development machine – like Environ(“COMPUTERNAME”) – so it saves the addin and you won’t lose dev changes.