Search code examples
c#vbavisioadd-on

Remove bad VBA code from Visio file after it is selected but before it is opened


I have a set of Visio drawing files that contain VBA code that is no longer needed (in fact, errors occur when trying to open a file as the module referenced in the VBA no longer exists).

Due to the nature of the add-on I'm working on, my users must keep Macros and VBA enabled. However, any file they open in Visio needs to have its VBA code automatically removed first.

I can hit a breakpoint in my code when the Visio application is launched, but before a file is selected to Open. I can also hit a breakpoint in my code after the file is selected and loaded in Visio. I cannot seem to find a way to get a break after the file is selected, but before Visio loads it.

Looking at the Visio Interop assemblies in C#, I can see Visio.Application events called "OnDocumentOpened" and "OnDocumentCreated", but they aren't triggered until 'after' the file has been loaded. I couldn't find anything called "BeforeDocumentOpened" or "BeforeDocumentCreated" unfortunately, which is basically exactly what I need. There are other events with similar names like "BeforeDocumentSave" and "BeforeDocumentClose", but obviously they are not what I'm looking for.

Any help would be greatly appreciated.

My Question: Are there any methods to capture when Visio attempts to open a drawing file but before it's actually opened? This is where I intend to remove the VBA code from the file, which I've already implemented. If not, any known workarounds to achieving something similar?

Example of the bad VBA I want to remove:

Private Sub Document_DocumentCreated(ByVal doc As Visio.Document)
    Call Initialize(doc)
End Sub

Private Sub Document_DocumentOpened(ByVal doc As Visio.Document)
    Call Initialize(doc)
End Sub

Private Sub Initialize(doc As Visio.Document)
    Dim myLib As Object
    Set myLib = CreateObject("MODULE_NAME") 'Errors here, since we got rid of the module
    ...
End Sub

Solution

  • I would not overdo it. You can upgrade your users. Like, provide a script (or some sort of functionality in the installer, or some button in the application) to update the diagrams. I.e. a separate function, just don't do it on opening the diagram. Since it is one-time operation, the users probably won't cry about that. And you won't add "garbage" one-time code to the application...

    Just to be clear: the event you are looking for "before document opened" does not exist.