Run macro automatically upon opening or closing document

M

Munchkin

How do I automatically run this macro when the workseet is either opened or
closed?


Rows("2:3").Select
Range("B2").Activate
Selection.EntireRow.Hidden = True
Rows("6:7").Select
Range("B6").Activate
Selection.EntireRow.Hidden = True
Range("C12").Select
End Sub
 
S

Simon Lloyd

Munchkin;373278 said:
How do I automatically run this macro when the workseet is either opened
or
closed?


Rows("2:3").Select
Range("B2").Activate
Selection.EntireRow.Hidden = True
Rows("6:7").Select
Range("B6").Activate
Selection.EntireRow.Hidden = True
Range("C12").Select
End SubIf you really want to run the same macro on open and close then put the
code below in the ThisWorkbook module, to be honest you select objects
when you don't need to and they perform no action, you will probably
want error handling too!

Code:
--------------------
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Rows("2:3").Select
Range("B2").Activate
Selection.EntireRow.Hidden = True
Rows("6:7").Select
Range("B6").Activate
Selection.EntireRow.Hidden = True
Range("C12").Select
End Sub


Private Sub Workbook_Open()
Rows("2:3").Select
Range("B2").Activate
Selection.EntireRow.Hidden = True
Rows("6:7").Select
Range("B6").Activate
Selection.EntireRow.Hidden = True
Range("C12").Select
End Sub
--------------------


--
Simon Lloyd

Regards,
Simon Lloyd
'The Code Cage' (http://www.thecodecage.com)
 
J

Jim Thomlinson

You have a problem with your on close. The changes are going to require the
file to be saved. That being said since the code is being run on open the on
close is not necessary. I would be inclined to just do this...

Private Sub Workbook_Open()
With Sheets("Sheet1") 'Change to the appropriate sheet name
.Rows("2:3").EntireRow.Hidden = True
.Rows("6:7").EntireRow.Hidden = True
.select
.Range("C12").Select
End with
End Sub

Right click the XL icon in the upper left corner of the Excel window and
select View Code. This takes you into the ThisWorkbook module. Post the code
above.
 

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

Top