excelvba

Predefined conditional compilation constants to determine if my VBA code is running in Word or Excel


Does Microsoft Office provide any predefined conditional compilation constants so I can determine if my VBA code is compiling in Word or Excel? I've already checked How to check which office applicaion vba code is running from but that didn't help because it requires that I define my own conditional compilation constants.

I want to write a module that I can import into any of my Office code whether it's Excel, Word, Visio, Outlook, etc., such that the code will compile without needing to add additional references or defining my own constants. The ActiveWorkbook and/or ActiveDocument objects won't compile depending on which Office app I'm running in.

For example, say I want to make a backup copy of the Office file I'm working on using code like this:

Sub ArchiveMe()
#if APPWORD then
     ActiveDocument.SaveAs ....
#ElseIf APPEXCEL then
     ActiveWorkbook.SaveAs ....
#Endif
End Sub

Since APPWORD and APPEXCEL are not predefined compilation constants my code won't compile because of the ActiveDocument and ActiveWorkbook Objects aren't recognized by all the Office apps.

If there are no such predefined compilation constants, I would also be interested in any other ways to accomplish my goal without having to add references or define my own compilation constants.


Solution

  • I don't know your ultimate goal, but maybe the following could solve your problem. Basic idea is to define variables as Object (in the example only app, but you might think about others). Using Object prevents that the compiler complains about unknown properties or methods. You just need to ensure that you call/use methods and properties that exists for the current application, else you will get a runtime error.

    Sub testApp()
        
        Dim app As Object, appName As String
        Set app = Application
        On Error Resume Next
        appName = app.Name
        On Error GoTo 0
        
        Select Case appName
            Case "Microsoft PowerPoint"
                Debug.Print app.ActivePresentation.Name
            Case "Microsoft Excel"
                Debug.Print app.ActiveWorkbook.Name
            Case "Microsoft Word"
                Debug.Print app.ActiveDocument.Name
            Case "Outlook"
                Dim nameSpace As Object
                Set nameSpace = app.GetNamespace("MAPI")
                Dim rootFolder As Object
                Set rootFolder = nameSpace.Folders.GetFirst
                Debug.Print rootFolder.Name
            Case Else
                Debug.Print "Sorry, app " & appName & " currently not supported."
        End Select
    End Sub
    

    (Sorry, don't have Visio available)