6

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.

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Hi, My macros are enable and the Option Explicit line was added, Although changing the declaration from Public to Private does not work as now when I run the program the WorkBook_Open procedure doesn't show up in the window
Where did you place the code? In ThisWorkbook or in a module? Test it with a MsgBox like I showed above. If macros are enabled this must work.
Hi, In this WorkBook, Let me try putting it in the VBA Editor
@Bonang No it must be in ThisWorkbook to make it work. See the Microsoft documentation link I gave in my answer. Follow it step by step.
@Bonang Just for my interest: What was the issue?
2

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

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

4 Comments

You should not use the Auto_Open event as this is for backwards compatibility only and will probably removed in future versions.
@Pᴇʜ I do not insist - I just provided an alternative 😉
Of course, nothing wrong with suggesting an alternative. I just thought it might be worth to mention that if you use it you bet on an old horse.
@Pᴇʜ Yeah... But this horse is more than 20 years and continue to work. As we say, "Old horse won't cause harm to furrow" 😆
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.