Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Clicking on Cells to execute code

Status
Not open for further replies.

mpadgett

IS-IT--Management
Jun 24, 2005
57
US
I've successfully written some code to execute a certain task if the user clicks on a cell. This is done by have a conditional statement in the Work Sheet code.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

If Target.Address = "$B$13" And Target.Value = "" Then
"code continues here but omitted to save space"

This code actually needs to needs to kick-off if the user clicks on any of the cells below:

$B$13 $C$13 $D$13 $E$13 $F$13
$B$14 $C$14 $D$14 $E$14 $F$14
$B$15 $C$15 $D$15 $E$15 $F$15

I'm trying to avoid a long nested IF statement that evaluate for each cell. I thought about the Select Case statement but I'm not sure if that would save me much coding.

Any thoughts or suggestions would be appreciated.

MP
 
Use Select Case. You can put all the cells in the same Case statement seperated by a comma.

Code:
Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

Dim sTemp As String

sTemp = Target.Address

Select Case sTemp

Case "$B$13", "$B$13", "$C$13", "$D$13", "$E$13"
   ' Insert code here
Case Else

End Select
End Sub
 

It can be simpler than that:
Code:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  If Not Intersect(Target, Range("B13:F15")) Is Nothing Then
    MsgBox ("You clicked " & Target.Address)
  End If
End Sub

 



You might also want to consider what happens if the user selects more than one cell in the selection.
Code:
if target.count>1 then
'...what?


Skip,

[glasses] [red][/red]
[tongue]
 

If selecting more than one cell implies to perform whatever it is you want to do on each of them, then this illustrates how that is possible:
Code:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim c As Range
  If Not Intersect(Target, Range("B13:F15")) Is Nothing Then
    For Each c In Intersect(Target, Range("B13:F15"))
      MsgBox ("You clicked " & c.Address)
    Next c
  End If
End Sub

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top