Home » excel » excel vba – How can VBA determine which software product it's currently running within..?

excel vba – How can VBA determine which software product it's currently running within..?

Posted by: admin April 23, 2020 Leave a comment

Questions:

Many software products have VBA incorporated into them. This includes Microsoft Office of course, but there are many 3rd-party products which have chosen to include VBA as well. A quick Google search turned up names like AutoCad, WordPerfect, PowerTerm, and ScriptWorx.

If one wishes to use #If/#EndIf directives to design a Sub or Function to work in multiple environments, how can VBA detect which one it’s currently running in..??

This is a bit different than detecting if a product is installed, in which case CreateObject() and an ErrorHandler could be used. Also, checking the References collection would not be definitive, since a VBA project might have multiple references to products other than the current one. For instance, an Access project might have a reference to Excel, and vice-versa (as many of mine do).

Say, I want to write a function that returns the name of the current file. Here’s some pseudo-code using Access and Excel as examples.

Public Function CurrentFilename() As String
    #If EnvironmentName="Access" Then
        CurrentFilename = Access.Application.CurrentProject.Fullname
    #ElseIf EnvironmentName="Excel" Then
        CurrentFilename = Excel.Application.ActiveWorkbook.Fullname
    #Else
        MsgBox "Current VBA software environment is not recognized."
    #End If
End Function

Is this possible..? If so, what’s the magic constant or function to replace ‘EnvironmentName’..?

How to&Answers:

I believe your best bet will be the Application.Name property. I can’t confirm it works for all VBA implementations, but it appears to be consistent with MS products.
From the MSDN reference: https://msdn.microsoft.com/en-us/library/office/aa221371(v=office.11).aspx