18.11.2014 Views

Microsoft Office

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Working with Excel Events 43<br />

MsgBox Msg, vbInformation<br />

End If<br />

End Sub<br />

Unfortunately, VBA can’t do much at all with Excel 2007’s ribbon. For example, there is no direct way to<br />

activate a particular ribbon tab. The next example uses the SendKeys statement to simulate keystrokes. In<br />

this case, it sends Alt+H, which is the Excel 2007 “keytip” equivalent of activating the Home tab in the ribbon.<br />

Sending the F6 keystroke removes the keytip letters from the ribbon.<br />

Private Sub Workbook_Open()<br />

Application.SendKeys (“%h{F6}”)<br />

End Sub<br />

The following example performs a number of actions when the workbook is opened. It maximizes Excel’s<br />

window, maximizes the workbook window, activates the sheet named DataEntry, and selects the first empty<br />

cell in column A. If a sheet named DataEntry does not exist, the code generates an error.<br />

Private Sub Workbook_Open()<br />

Application.WindowState = xlMaximized<br />

ActiveWindow.WindowState = xlMaximized<br />

Worksheets(“DataEntry”).Activate<br />

Range(“A1”).End(xlDown).offset(1,0).Select<br />

End Sub<br />

Using the SheetActivate event<br />

The following procedure executes whenever the user activates any sheet in the workbook. The code simply<br />

selects cell A1. Including the On Error Resume Next statement causes the procedure to ignore the error<br />

that occurs if the activated sheet is a chart sheet.<br />

Private Sub Workbook_SheetActivate(ByVal Sh As Object)<br />

On Error Resume Next<br />

Range(“A1”).Select<br />

End Sub<br />

An alternative method to handle the case of a chart sheet is to check the sheet type. Use the Sh argument,<br />

which is passed to the procedure.<br />

Private Sub Workbook_SheetActivate(ByVal Sh As Object)<br />

If TypeName(Sh) = “Worksheet” Then Range(“A1”).Select<br />

End Sub<br />

Using the NewSheet event<br />

The following procedure executes whenever a new sheet is added to the workbook. The sheet is passed to<br />

the procedure as an argument. Because a new sheet can be either a worksheet or a chart sheet, this procedure<br />

determines the sheet type. If it’s a worksheet, it inserts a date and time stamp in cell A1.<br />

Private Sub Workbook_NewSheet(ByVal Sh As Object)<br />

If TypeName(Sh) = “Worksheet” Then _<br />

Range(“A1”) = “Sheet added “ & Now()<br />

End Sub<br />

749

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!