Exceute macro when cell is clicked

K

Kent McPherson

How do I execute a specific macro when I click on a cell? For example, if I
click in cell B3, I want to run a macro. Suggestions?
 
P

Paul C

Use the Worksheet_SelectionChange method.\

This would go on the individual sheet in the VBA Editor

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Address <> "$B$3" Then Exit Sub
Do Stuff
End Sub
 
G

Gary''s Student

One limitation of Paul's approach is that the macro would get also get called
if the cell were entered via the ARROW keys or the TAB key or even the enter
key.

Another approach is to Insert a hyperlink in B3 to a Place in the Document
(namely B3). At first blush, this seems a little silly (why insert a
hyperlink that goes nowhere?). We now can trap the click with a hyperlink
follow event macro:

Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
If Target.Parent.Address = "$B$3" Then
Call hello
End If
End Sub

Now the cell will perform just like a button. You can even add a mouse-over
popup message if you want.
 
K

Kent McPherson

Yes, this is great. Thanks.

Paul C said:
Use the Worksheet_SelectionChange method.\

This would go on the individual sheet in the VBA Editor

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Address <> "$B$3" Then Exit Sub
Do Stuff
End Sub
 
K

Kent McPherson

Very cool. I love this newsgroup!

Gary''s Student said:
One limitation of Paul's approach is that the macro would get also get
called
if the cell were entered via the ARROW keys or the TAB key or even the
enter
key.

Another approach is to Insert a hyperlink in B3 to a Place in the Document
(namely B3). At first blush, this seems a little silly (why insert a
hyperlink that goes nowhere?). We now can trap the click with a hyperlink
follow event macro:

Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
If Target.Parent.Address = "$B$3" Then
Call hello
End If
End Sub

Now the cell will perform just like a button. You can even add a
mouse-over
popup message if you want.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top