简体   繁体   中英

Merging multiple Worksheet_SelectionChange

I have got no problem in running one Private Sub Worksheet_SelectionChange , but when i add multiple Worksheet_SelectionChange events it is not running. Later, i came to know that it is not possible running different worksheet selection change events in the same sheet.

I am having four different Private Sub Worksheet_SelectionChange events, trying to merge them with the help of various sites but none worked to me, as per my understanding. Could i get some help, 1.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim cells1 As Range
Set cells1 = ActiveSheet.Range("B1:B27")
If Not (Intersect(Target, cells1) Is Nothing) Then
   ActiveSheet.Range("B30").Value = Target.Value
End If
End Sub

2.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim cells2 As Range
Set cells2 = ActiveSheet.Range("C1:C27")
If Not (Intersect(Target, cells2) Is Nothing) Then
   ActiveSheet.Range("C30").Value = Target.Value
End If
End Sub

3.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim cells3 As Range
Set cells3 = ActiveSheet.Range("S1:S27")
If Not (Intersect(Target, cells3) Is Nothing) Then
   ActiveSheet.Range("S30").Value = Target.Value
End If
End Sub

4.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim cells4 As Range
Set cells4 = ActiveSheet.Range("T1:T27")
If Not (Intersect(Target, cells4) Is Nothing) Then
   ActiveSheet.Range("T30").Value = Target.Value
End If
End Sub

I appreciate your help. Thank you.

You can use a switch ( select case ) within your change event to allow options for which will occur.

Mock-up:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Target.Row > 27 then Exit Sub
    Select Case Target.Column
        Case 2, 3, 19, 20
            Cells(30,Target.Column).Value = Target.Value
    End Select
End Sub

I have added the Exit Sub check for if the row > 27, as your ranges are 1:27, for each of the Columns. This replaces the Intersect() check.

You perform the same action based on the Target.Column , so that is the only other parameter to verify and utilize.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM