Running a VBA Macro

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello,

It is possible to run a VBA macro automatically when I open a workbook
instead of opening the workbook and then run the VBA macro from the menu
"Tools" "Macro?"
Thanks,
 
Jeff,

In the Code window of "ThisWorkbook" in the VBA Editor (Click on
"ThisWorkbook" and press F7), paste the following (for example)

Private Sub Workbook_Open()
'MsgBox ("Good Morning - I'm Open!")
CreateObject("WScript.Shell").Popup "Hello!", 1, " Hello for 1 second! "
End Sub

To run a macro before the workbook closes, try:

Private Sub Workbook_BeforeClose(cancel As Boolean)
'MsgBox ("Leaving Workbook - Goodbye!")
End Sub

And to run code when a particul;ar worksheet is opened or closed, try
pasting these into their code windows in the same way as shown above, by
clicking on the worksheet name and pressing F7

None of these will work if they're in a normal module - they have to be in
the module for the workbook or the appropriate worksheet.

Private Sub Worksheet_Activate()
MsgBox ("Activating Sheet 1!")
End Sub

Private Sub Worksheet_Deactivate()
MsgBox ("Leaving Sheet 1!")
End Sub

Hope these help

Pete


The Createobject is nothing to do with this, it's a handy way of puting a
wait into a macro - the '1' is the number of seconds for which the delay
lasts.
 
Use the Workbook_Open event:

Sub Workbook_Open()
MyMacro
End Sub

where MyMacro is the name of the macro you wish to run.
To use, press ALT+F11 and place the macro
in "ThisWorkbook" module.

HTH
Jason
Atlanta, GA
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top