grNadpa
grNadpa

Reputation: 79

run macro when open workbook

I have done a search. The most relevant suggests the macro name of "workbook_open" But I still must manually invoke the module. Here's what I've coded. (Any other suggestions welcome as this is my first vba script -- at age 73)

Sub Workbook_Open()  
  Dim lastRow As Long     'last row with data  
  Dim thisDate As Double  'start timestamp  
  thisDate = Now()  
  With Sheets("Pressure Log")  
    lastRow = .Range("B" & .Rows.Count).End(xlUp).Row 'populate next row with date/time  
    Range("B" & lastRow).Offset(1) = Format(thisDate, "dddd")  
    Range("B" & lastRow).Offset(1, 1) = Format(thisDate, "mm/dd/yyyy")  
    Range("B" & lastRow).Offset(1, 2) = Format(thisDate, "hh:mm AM/PM")  
    Range("B" & lastRow).Offset(1, 3).Select 'position for user data  
  End With  
End Sub  

Upvotes: 2

Views: 4535

Answers (2)

JohnyL
JohnyL

Reputation: 7122

Adding to Mathieu's answer, there's also one more way to run code upon opening workbook: you can create Auto_Open procedure in standard module. Warning! This feature can be removed in next versions of Office, however it's still alive! 😉

In standard module:

Sub Auto_Open()
    ' Your code
End Sub

In the same way you can use Auto_Close procedure instead of BeforeClose event handler.

Upvotes: 2

Mathieu Guindon
Mathieu Guindon

Reputation: 71157

In the Visual Basic Editor (VBE), bring up the Project Explorer (Ctrl+R), then double-click the ThisWorkbook module (or right-click it and select "View Code"):

ThisWorkbook in the VBE's Project Explorer

That will bring up the ThisWorkbook module's code-behind. ThisWorkbook represents the workbook that's hosting your VBA project; it's a special type of module that inherits all the members of the Excel.Workbook class, which can represent any Excel workbook.

At the top of the code pane, you will notice two dropdowns:

code pane

Select Workbook from the left-hand dropdown; the VBE generates an event handler procedure for the Open event, automatically:

Workbook_Open() procedure created

Notice the right-hand dropdown now says Open - if you click that dropdown, you'll find that it lists every event that a Workbook can handle; selecting one will automatically generate a method with the correct signature/prototype for it.

Now take your code and put it in that event handler procedure, save - and you're set! Next time that workbook is opened with macros enabled, that event handler will be invoked, and your macro will run.

Have fun! It's never too late to learn!

Upvotes: 7

Related Questions