Please Note: This article is written for users of the following Microsoft Excel versions: 2007, 2010, and 2013. If you are using an earlier version (Excel 2003 or earlier), this tip may not work for you. For a version of this tip written specifically for earlier versions of Excel, click here: Mouse Click Event in VBA.

Mouse Click Event in VBA

by Allen Wyatt
(last updated October 26, 2015)

5

Supriyo 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

ExcelTips is your source for cost-effective Microsoft Excel training. This tip (12514) applies to Microsoft Excel 2007, 2010, and 2013. You can find a version of this tip for the older menu interface of Excel here: Mouse Click Event in VBA.

Author Bio

Allen Wyatt

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. ...

MORE FROM ALLEN

Changing Datasheet Column Width

To see information in a datasheet better, you may need to adjust column width.

Discover More

Creating New Windows

If you need to look at different parts of the same worksheet at the same time, the answer is to create windows for your data. ...

Discover More

Selecting Tabs in Dialog Boxes

Dialog boxes normally present information in a series of tabs. If you want to move from tab to tab without taking your hands ...

Discover More

Professional Development Guidance! Four world-class developers offer start-to-finish guidance for building powerful, robust, and secure applications with Excel. The authors show how to consistently make the right design decisions and make the most of Excel's powerful features. Check out Professional Excel Development today!

More ExcelTips (ribbon)

Changing the Default Drive

Do you have a macro that need to read and write files? If so, then there is a good chance you need to specify the default ...

Discover More

Running a Macro when a Worksheet is Deactivated

When you change from one worksheet to another, you may want to have Excel automatically run a macro for the worksheet you are ...

Discover More

Bypassing the BeforeClose Event

Hold down the Shift key as you open a workbook, and Excel bypasses any "startup macros" that may be in the workbook. If you ...

Discover More
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

View most recent newsletter.

Comments

If you would like to add an image to your comment (not an avatar, but an image to help in making the point of your comment), include the characters [{fig}] in your comment text. You’ll be prompted to upload your image when you submit the comment. Maximum image size is 6Mpixels. Images larger than 600px wide or 1000px tall will be reduced. Up to three images may be included in a comment. All images are subject to review. Commenting privileges may be curtailed if inappropriate images are posted.

What is one more than 9?

2015-10-26 13:49:40

Michael (Micky) Avidan

@To whom it may concern,

Please check the two Event-Macros:

Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean)
MsgBox "Cell: " & Target.Address & " was a Right Clicked"
End Sub

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
MsgBox "Cell: " & Target.Address & " was Double clicked"
End Sub
--------------------------
Michael (Micky) Avidan
“Microsoft® Answers" - Wiki author & Forums Moderator
“Microsoft®” MVP – Excel (2009-2016)
ISRAEL


2014-10-07 14:28:40

Bigger Don

Looking at this a little further I found out I was on track. Alan does have some tips that are helpful in understanding how to solve the problem.
* Running Macros in the Background
* Aborting a Macro and Retaining Control
* Pausing Macros for User Input
* Working while a Macro is Running

Here is one method. I have adaptations of this based on different assumptions and style decisions.

The front end is a UserForm (ufmStartPauseResumeStop01) with the following controls
* Command button (btnStart)
* Toggle button (gbPauseResume)
* Check box (cbxStop)

Here's the code:

Userform ufmStartPauseResumeStop01

Private Sub tgbPauseResume_AfterUpdate()
If tgbPauseResume Then
Me.cbxStop.Enabled = True
Me.cbxStop = False
tgbPauseResume.Caption = "Resume"
Else
tgbPauseResume.Caption = "Pause"
End If
End Sub

Private Sub UserForm_Activate()
Me.cbtStart.Enabled = True
Me.tgbPauseResume.Enabled = False
Me.cbxStop.Enabled = False
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
' Prevents use of the Close button if the control macro called by the Start button is running
If Me.tgbPauseResume.Enabled And CloseMode = vbFormControlMenu Then
' An alternative to "Me.tgbPauseResume.visible" would be "Not Me.cbtStart.visible"
MsgBox "Close button disabled during run."
Cancel = True
End If
End Sub

****************************

Module Mod_01_Enabled

Option Explicit

' !!! The following Sub is the core of the answer to your question.

StartPauseResumeStop_Enabled()
ufmStartPauseResumeStop01.Show
End Sub

Private Sub ControlWithFormEvents_Enabled()
' This is the control module
Dim cel As Range
Set cel = ThisWorkbook.Sheets(1).Range("A1")
cel.Parent.Activate
cel.Select
Do ' Loop runs until the Check Box for stopping the run is clicked on _
See comments in UserForm object module
cel.Value = AddAndDivide(cel)
If ufmStartPauseResumeStop01.tgbPauseResume Then
Do
DoEvents
Loop Until Not ufmStartPauseResumeStop01.tgbPauseResume
End If
DoEvents
Loop Until ufmStartPauseResumeStop01.cbxStop
ufmStartPauseResumeStop01.cbtStart.Enabled = True
ufmStartPauseResumeStop01.tgbPauseResume.Enabled = False
ufmStartPauseResumeStop01.cbxStop = False
ufmStartPauseResumeStop01.cbxStop.Enabled = False
End Sub

****************************
Module Mod_CommonSub

Option Explicit

Function AddAndDivide(cel As Range)
If Len(cel.Value) = 0 Then cel.Value = 0
If IsNumeric(cel.Value) Then
If CInt(Left(CStr(cel.Value), 1)) > 2 Then
AddAndDivide = cel.Value / 2
Else
AddAndDivide = cel.Value + 1
End If
End If
End Function


2014-10-07 12:01:50

Barry

@Richard

To flesh out what Don has said you can use a Userform in "modeless" mode, or a command button on a worksheet itself.

To allow a click of a button, your repetitive macro needs to relinquish control to the User during execution in order for Excel to register the mouse click. You do this by including a "DoEvents" command within your repetitive loop (there are other ways as well using the Onkey or Ontime functions).


2014-10-06 13:29:19

Don

@Richard1941

I don't have a solution but I do have a thought or two.

I would try to implement a userform with a Pause/Resume toggle button. Clicking the button would change the state of the button (and the caption, of course).

When the code is running and hits the suspend point(s) it checks the state of the button, then continues on or suspends work.

You would also want to use the Click event handler for the button, checking the state change and resuming as appropriate.

Also, Alan has a hint or more on running macros in background mode. You might need to incorporate that information


2014-10-02 03:46:37

richard1941

Whlie my macro is running a repetitive task in a loop, I hit ESC and get out of it, wherever it is. What I would like is a way to get out only after finishing the complete task (a montecarlo simulation) so that it can be resumed where it was interrupted. Just detecting a keypress or mouse click somewhere that the macro could test at the end of the loop would be great.

I am just a beginner at excel VBA macros, and have been so for ten years.


This Site

Got a version of Excel that uses the ribbon interface (Excel 2007 or later)? This site is for you! If you use an earlier version of Excel, visit our ExcelTips site focusing on the menu interface.

Newest Tips
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

(Your e-mail address is not shared with anyone, ever.)

View the most recent newsletter.