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.

Introducing Visual Basic for Applications 39<br />

FIGURE 39.9<br />

The TimeStamp procedure was generated by Excel’s macro recorder.<br />

Double-click the module in the Projects window to activate the module so that you can examine the macro.<br />

It should consist of the following code:<br />

Sub TimeStamp()<br />

‘<br />

‘ TimeStamp Macro<br />

‘ Keyboard Shortcut: Ctrl+Shift+T<br />

‘<br />

ActiveCell.FormulaR1C1 = “=NOW()”<br />

Selection.Copy<br />

Selection.PasteSpecial Paste:=xlPasteValues, _<br />

Operation:= xlNone, SkipBlanks _<br />

:=False, Transpose:=False<br />

Application.CutCopyMode = False<br />

End Sub<br />

The procedure has four statements. The first inserts the NOW() formula into the active cell. The second<br />

statement copies the cell. The third statement, which is displayed on three lines (the underscore character<br />

means that the statement continues on the next line), pastes the Clipboard contents (as a value) to the current<br />

selection. The fourth statement cancels the moving border around the selected range.<br />

You may notice that the macro recorded some actions that you didn’t take. For example, it specified several<br />

options for the PasteSpecial operation. Recording actions that you don’t specifically make is just a<br />

byproduct of the method that Excel uses to translate actions into code.<br />

Testing the macro<br />

When Excel is active, activate a worksheet. (It can be in the workbook that contains the VBA module or in<br />

any other workbook.) Select a cell and press Ctrl+Shift+T. The macro immediately enters the current date<br />

and time into the cell. You may need to widen the column to see the date and time. To widen the column<br />

automatically, just add this statement to the end of the macro (before the End Sub statement):<br />

ActiveCell.EntireColumn.AutoFit<br />

691

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

Saved successfully!

Ooh no, something went wrong!