With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He is president of Sharon Parq Associates, a computer and publishing services company.
Learn more about Allen...
Please Note: This article is written for users of the following Microsoft Excel versions: 97, 2000, 2002, and 2003. If you are using a later version (Excel 2007 or later), this tip may not work for you. For a version of this tip written specifically for later versions of Excel, click here: Putting an X in a Clicked Cell.
Wendy has a worksheet that has quite a bit of data in it, with the main data in the range C3:P312. She would like to have a macro that, if she clicks a cell in this data range, would put an "x" into the cell.
There is no event that Excel can recognize as a "click" on a cell. Perhaps the closest event is the SelectionChange event, which is triggered every time the cell selection changes. The event handler could then check to make sure that the cell selection is within the C3:P312 range, and then place an "x" in the cell if it is. The following event handler will do that:
Private Sub Worksheet_SelectionChange(ByVal Target As Range) Dim rInt As Range Dim rCell As Range Set rInt = Intersect(Target, Range("C3:P312")) If Not rInt Is Nothing Then For Each rCell In rInt rCell.Value = "x" Next End If Set rInt = Nothing Set rCell = Nothing End Sub
There is a problem with this approach, however: Not only will the SelectionChange event trigger when you click on a different cell, it also triggers if you use the keyboard to move from one cell to another in the worksheet. This means that if you use the keyboard to move about the worksheet you will leave a tail of "x" characters in each cell you transit.
One way around this is to change the event that triggers the check and change of the cells. While Excel has no "click" event, there is a "double click" event. This means that you can change the cell on which you double click, as shown here:
Private Sub Worksheet_BeforeDoubleClick( _ ByVal Target As Range, Cancel As Boolean) Dim rInt As Range Dim rCell As Range Set rInt = Intersect(Target, Range("C3:P312")) If Not rInt Is Nothing Then For Each rCell In rInt rCell.Value = "x" Next End If Set rInt = Nothing Set rCell = Nothing Cancel = True End Sub
ExcelTips is your source for cost-effective Microsoft Excel training. This tip (3378) applies to Microsoft Excel 97, 2000, 2002, and 2003. You can find a version of this tip for the ribbon interface of Excel (Excel 2007 and later) here: Putting an X in a Clicked Cell.
Save Time and Supercharge Excel! Automate virtually any routine task and save yourself hours, days, maybe even weeks. Then, learn how to make Excel do things you thought were simply impossible! Mastering advanced Excel macros has never been easier. Check out Excel 2010 VBA and Macros today!