Toggling a Boolean property

A Boolean property is one that is either True or False . The easiest way to toggle a Boolean property is to use the Not operator, as shown in the following example, which toggles the wrapText property of a selection.

Sub ToggleWrapText()

' Toggles text wrap alignment for selected cells If TypeName(Selection) = "Range" Then

Selection.WrapText = Not ActiveCell.WrapText End If End Sub

Note that the active cell is used as the basis for toggling. When a range is selected and the property values in the cells are inconsistent (for example, some cells are bold, and others are not), it is considered mixed, and Excel uses the active cell to determine how to toggle. If the active cell is bold, for example, all cells in the selection are made not bold when you click the Bold button. This simple procedure mimics the way Excel works, which is usually the best practice.

Note also that this procedure uses the TypeName function to check whether the selection is a range. If the selection isn't a range, nothing happens.

You can use the Not operator to toggle many other properties. For example, to toggle the display of row and column borders in a worksheet, use the following code:

ActiveWindow.DisplayHeadings = Not _ ActiveWindow.DisplayHeadings

To toggle the display of grid lines in the active worksheet, use the following code:

ActiveWindow.DisplayGridlines = Not _ ActiveWindow.DisplayGridlines

0 0

Post a comment