简体   繁体   中英

Automatically Run VBA Code when an Excel Workbook Opens

I have VBA code in I would like to run when the Excel workbook is opened.

I tried creating a public procedure in the sheet the code is supposed to run in:

Public Sub Workbook_Open 
    ' Some code here
End Sub

It does not run when the workbook opens.

It is supposed to create a combobox in one of the cells and then fill it with information from the database.

Make sure that the code is in the ThisWorkbook scope of the VBA editor and not in a module or worksheet:

Option Explicit

Private Sub Workbook_Open()
    MsgBox "Autorun works!"
    'your code here
End Sub

And make sure that your macros are enabled .

For details also see Microsoft's documentation: Automatically run a macro when opening a workbook .

Adding to @Pᴇʜ's answer, you can also use the following procedure in standard module:

Sub Auto_Open()
    '// Your code here...
End Sub

You are trying to create an event procedure that activates when you open a book. Go to thisworkbook in the VBA editor and choose workbook open procedure from the drop down list above the coding window, or you can type manually:

Private Sub Workbook_Open()

End Sub

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