XL 2010 À propos de Private Sub Worksheet_SelectionChange(ByVal Target As Range)

Magic_Doctor

XLDnaute Barbatruc
Bonjour,
J’ai plusieurs cellules qui, quand on clique dessus, déclenchent automatiquement une macro paramétrée : ActionCellBouton (x As Byte).
Toutes ces cellules sont nommées : CellBouton1, CellBouton2…
Le « x » de la macro n’est ni plus ni moins que le suffixe numérique du nom de chaque cellule nommée.

Voici ma routine qui marche correctement :
VB:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    If Not Intersect(Target, [CellBouton1]) Is Nothing Then
        ActionCellBouton (1)
    End If
    
    If Not Intersect(Target, [CellBouton2]) Is Nothing Then
        ActionCellBouton (2)
    End If
    
    If Not Intersect(Target, [CellBouton3]) Is Nothing Then
        ActionCellBouton (3)
    End If
    
    If Not Intersect(Target, [CellBouton4]) Is Nothing Then
        ActionCellBouton (4)
    End If

End Sub
Supposons maintenant qu’il y ait, pourquoi pas, 250 cellules nommées selon le même principe. Existerait-il un moyen d’éviter de réécrire à chaque fois :
Code:
If Not Intersect(Target, [CellBouton1]) Is Nothing Then
        ActionCellBouton (1)
End If
Jusqu’à :
Code:
If Not Intersect(Target, [CellBouton250]) Is Nothing Then
        ActionCellBouton (250)
End If
En écrivant un truc du genre :
Code:
If Not Intersect(Target, Range("CellBouton" & x)) Is Nothing Then
       ActionCellBouton (x)
End If

C’est essentiellement par curiosité que je pose la question.
 

Magic_Doctor

XLDnaute Barbatruc
Bonsoir job,

Tu viens de me couper élégamment l'herbe sous les pieds. Inspiré, j'avais rédigé ceci :
VB:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)

Dim x As Byte

    On Error Resume Next 'sinon problèmes...
    
    If Left(Target.Name.Name, 10) = "CellBouton" Then x = Right(Target.Name.Name, 1)
    
    If Not Intersect(Target, Range("CellBouton" & x)) Is Nothing Then ActionCellBouton (x)
    
End Sub
Ça marche, mais ta solution est plus subtile, donc adoptée !

Merci à toi, et une très bonne fin de soirée estivale (ici on se les pèle !!!).
 

Discussions similaires

Statistiques des forums

Discussions
312 103
Messages
2 085 322
Membres
102 862
dernier inscrit
Emma35400