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.

VBA Examples 44<br />

Turning off screen updating<br />

You’ve probably noticed that when you execute a macro, you can watch everything that occurs in the<br />

macro. Sometimes, this view is instructive; but after you get the macro working properly, it can be annoying<br />

and slow things considerably.<br />

Fortunately, you can disable the normal screen updating that occurs when you execute a macro. Insert the<br />

following statement to turn off screen updating:<br />

Application.ScreenUpdating = False<br />

If, at any point during the macro, you want the user to see the results of the macro, use the following statement<br />

to turn screen updating back on:<br />

Application.ScreenUpdating = True<br />

Preventing alert messages<br />

One benefit of using a macro is that you can perform a series of actions automatically. You can start a macro<br />

and then get a cup of coffee while Excel does its thing. Some operations cause Excel to display messages<br />

that must be attended to, however. For example, if your macro deletes a sheet, you see the message that is<br />

shown in the dialog box in Figure 44.3. These types of messages mean that you can’t execute your macro<br />

unattended.<br />

FIGURE 44.3<br />

You can instruct Excel not to display these types of alerts while a macro is running.<br />

To avoid these alert messages, insert the following VBA statement:<br />

Application.DisplayAlerts = False<br />

To turn alerts back on, use this statement:<br />

Application.DisplayAlerts = True<br />

Simplifying object references<br />

As you may have discovered, references to objects can get very lengthy — especially if your code refers to an<br />

object that’s not on the active sheet or in the active workbook. For example, a fully qualified reference to a<br />

Range object may look like this:<br />

Workbooks(“MyBook.xlsx”).Worksheets(“Sheet1”).Range(“IntRate”)<br />

If your macro uses this range frequently, you may want to use the Set command to create an object variable.<br />

For example, to assign this Range object to an object variable named Rate, use the following statement:<br />

Set Rate= Workbooks(“MyBook.xlsx”).Worksheets(“Sheet1”).Range(“IntRate”)<br />

767

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

Saved successfully!

Ooh no, something went wrong!