rubberduck-vba / Rubberduck

Every programmer needs a rubberduck. COM add-in for the VBA & VB6 IDE (VBE).
https://rubberduckvba.com
GNU General Public License v3.0
1.92k stars 302 forks source link

VBE.ActiveVBProject is a lie! #3436

Closed retailcoder closed 3 years ago

retailcoder commented 7 years ago

Repro: open up Excel with the default empty document, bring up the VBE, then close the host document.

I have no document in the host application, yet the following commands are happily enabled regardless:

Turns out, in a 32-bit Excel 2010 host at least, the immediate pane outputs this:

?Application.VBE.ActiveVBProject.VBComponents.Count
 4
?ThisWorkbook.Name '' run-time error 429 / ActiveX can't create object

So... we've been fooled (again!) by the VBIDE API: VBE.ActiveVBProject is a lie - it being non-null does NOT mean there's an active VBA project in the IDE!

However, if I instead open up Excel with the default empty document, close it, and then bring up the VBE, then ActiveVBProject will be Nothing, and the menu items listed above will be disabled accordingly.

Somehow the VBE is holding on to that ghost project, which is making us look like we don't know the state of the IDE.

SystemsModelling commented 7 years ago

A similar thing happens when userform references or objects representing other applications go out of scope or become invalid for whatever reason - the object is not Nothing, but you can't access any properties. I usually resort to testing for some property that should always be there like .Name and if that errors, treat the object as Nothing.