简体   繁体   中英

How do I run code on Excel startup (not workbook_open)?

I'm looking for a way to run code on opening an excel file, but not from the workbook_open method.

Like with a specific name "main_tables.xlsx", and excel on opening, runs custom macros, that are not from the said file.

Any ideas? Thanks.

You can use an Add-In.

Create an add-in with the following code in the ThisWorkbook module:

Private WithEvents app As Application

' This will run when any workbook is opened.
Private Sub app_WorkbookOpen(ByVal Wb As Workbook)
    ' Check if this add-in is opening versus any other workbook.
    If Not Wb Is Me Then
        ' Another workbook is opening - do something...
        MsgBox Wb.Name
    End If
End Sub

' This will run when the add-in workbook is opened.
Private Sub Workbook_Open()
    ' Set the app variable so that we can listen for WorkbookOpen event
    Set app = Application
End Sub

Save this as an add-in in the add-in folder (usually C:\\Users\\\\AppData\\Roaming\\Microsoft|AddIns) by choosing File -> Save As and selecting the Excel Add-in (*.xlam) file type.

Then in File -> Options -> Add-ins choose Manage Excel Add-ins and press Go.... This brings up a list of add-ins to start automatically. Tick the add-in you just created.

Now, when you open any workbook, the add-in code will run.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM