Question

Apologies in advance if this ends up being generic. I have done some research on this and drawn a complete blank.

Excel is great, I love Excel. So much so that the "Recent Documents" section is of almost no use to me as I use that many spreadsheets in an insane amount of locations.

I have been researching a way to log (using VBA as an AddIn) documents when they are opened. Even if it is into something as simple as a text file with the date, however I cannot figure out how to have the VBA code "know" when a file is opened (which, along with outputting to a Text file, is all I want it to do at this stage).

Is there a way to have the VBA look for this action from within an excel instance?

Was it helpful?

Solution

The following steps (adapted from the excellent post at http://www.cpearson.com/excel/AppEvent.aspx ) is the "minimally viable" way to do what you need.

  1. open a new workbook
  2. open the VB editor
  3. Insert a class module; in the properties window, set class name to CExcelEvents
  4. Add the following code in the class module:
    Private WithEvents App As Application

    Private Sub Class_Initialize()
        Set App = Application
        MsgBox "initialized the class!"
    End Sub

    Private Sub App_WorkbookOpen(ByVal Wb As Workbook)
        MsgBox "New Workbook was opened: " & Wb.Name
    End Sub

  5.  Right-click on the "ThisWorkbook" element in the project explorer, and select "View Code"
  6.  Add the following code:

Private XLApp As CExcelEvents

Private Sub Workbook_Open()
    Set XLApp = New CExcelEvents
End Sub

This creates an instance of the CExcelEvents class, and "turns on event handling" when the addIn is loaded.

Finally, save the file as myEvents.xlam in the location where addIns are stored - this varies depending on your machine...

If you now close the file, and add the addIn (again, depends on your environment whether that is from the Developer ribbon or the Tools menu), you should see a dialog box that says "initialized the class!". This shows the addIn is properly installed and working.

Now, when you open a workbook, another message box will appear: "New Workbook was opened: " with the name.

Obviously you will want to get rid of the message boxes, and put in some "useful" code that does whatever you want to do (for example, log the name of the workbook to a file). It sounds to me like you don't need help with the latter - if I am wrong then please let me know.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top