bottom
Great ExcelTips!
         
Your e-mail address is safe!
Close Note

Tips.Net > ExcelTips Home > Macros > Mouse Click Event in VBA

Mouse Click Event in VBA

Summary: Excel does not have a dedicated “mouse click” event that you can trap and handle. You can, however, use the SelectionChange event (as described in this tip) to run a macro whenever a different cell or range of cells is selected in the workbook. (This tip works with Microsoft Excel 97, Excel 2000, Excel 2002, and Excel 2003.)

Supriyo Dasgupta asked if there is a mouse event handler in VBA. He wants a value inserted in a cell when that cell is clicked on.

The standard way to do this is with the SelectionChange event. Every time the selection changes in the worksheet, the event is triggered. The event doesn't just trigger when a cell is clicked on, but also if someone presses a cursor control key that results in a different cell being selected.

As an example, let's say that you wanted cell B5 to contain the value 10 whenever that cell is selected. To implement that, you could use the following:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Not Intersect(Target, Range("B5")) Is Nothing Then _
      Range("B5").Value = 10
End Sub

This code is added to one of the sheet objects in the Project Explorer area of the VB Editor. Double-click the worksheet you want the event handler to apply to, and then add the macro to the resulting code window.

When the SelectionChange event is triggered, the target (the cell range being selected) is passed to the handler. The macro then checks to see if the target range contains cell B5, and if it does, stuffs the value 10 into cell B5. If you want to make sure that the macro only stuffs information into B5 if only B5 (the single cell) is selected, you can use this version of the macro:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Target.Address = Range("B5").Address Then _
      Range("B5").Value = 10
End Sub

Tip #3070 applies to Microsoft Excel versions: 97 | 2000 | 2002 | 2003


Save Time! You can have this tip (and several hundred just like it) in the ExcelTips annual archives. Imagine having over 400 tips available at your fingertips, in each annual volume.

Helpful Links

Ask an Excel Question
Make a Comment

Tips.Net Home
Vital News Home

ExcelTips FAQ
ExcelTips Premium

Learn Access Now

Beauty Tips
Car Tips
Cleaning Tips
College Tips
Cooking Tips
Excel2007 Tips
ExcelTips
Family Tips
Gardening Tips
Health Tips
Home Tips
Money Tips
Pet Tips
Word2007 Tips
WordTips

Advertise on the
ExcelTips Site

 

Great Info!

Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your e-mail address and click "Subscribe."
     
(Your e-mail address will never be shared with anyone, ever.)