The Active Properties

The Application object provides many shortcuts that allow you to refer to active objects without naming them explicitly. This makes it possible to discover what is currently active when your macro runs. It also makes it easy to write generalized code that can be applied to objects of the same type with different names.

The following Application object properties are global properties that allow you to refer to active

objects:

ActiveCell

ActiveChart

ActivePrinter

ActiveSheet

ActiveWindow

□ ActiveWorkbook

If you have just created a new workbook and want to save it with a specific filename, using the ActiveWorkbook property is an easy way to return a reference to the new Workbook object:

Workbooks.Add

ActiveWorkbook.SaveAs Filename:="C:\Data.xls"

If you want to write a macro that can apply a bold format to the currently selected cells, you can use the Selection property to return a reference to the Range object containing the selected cells:

Selection.Font.Bold = True

Be aware that Selection will not refer to a Range object if another type of object, such as a Shape object, is currently selected or the active sheet is not a worksheet. You might want to build a check into a macro to ensure that a worksheet is selected before attempting to enter data into it:

If TypeName(ActiveSheet) <> "Worksheet" Or _

TypeName(Selection) <> "Range" Then

MsgBox "You can only run this macro in a range",

, vbCritical

Exit Sub

End If

0 0

Post a comment