VBA – Comment sortir un sous set si une condition n'est pas vraie

Je cherche votre aide. Eh bien, j'ai un sous-divisé dans beaucoup de proc

Sub Go Call Proc1 Call Proc2 Call Proc3 Call Proc4 End Sub 

Dans Proc1, je fais l'appariement des valeurs et je vérifie si les cellules sont vides, etc. Je souhaite donc quitter le Sub Go et arrêter la mise en marche de la macro si une condition n'est pas vraie.

J'ai testé End, Exit Sub, mais il passe du test 1 au test 2.

Existe-t-il une méthode pour aller directement au dernier End Sub (c'est-à-dire Sub Go!)

Solution 1: Modification de Sub to Fonctions:

 Function Proc1() As Boolean 'Do some check If SomeCheckAreWrong Then Proc1 = False Else 'Normal treatment Proc1 = True End If End Function Sub Go() If Proc1 Then 'do proc2 only if proc1 returned True If Proc2 Then '... End If End If End Sub 

Solution 2: Augmenter et attraper l'erreur

 Sub Proc1() 'Do some check If SomeCheckAreWrong Then Err.Raise vbObjectError + 1 Else 'Normal treatment End If End Sub Sub Go() On Error GoTo exit_with_error Proc1 Proc2 '... exit_with_error: End Sub 

Solution 3: avec variable globale

 Global DoNotContinue As Boolean Sub Proc1() 'Do some check If SomeCheckAreWrong Then DoNotContinue = True Else 'Normal treatment End If End Sub Sub Go() DoNotContinue = False Proc1 If DoNotContinue Then Exit Sub Proc2 If DoNotContinue Then Exit Sub '... End Sub 

Voici un moyen:

 Sub Main() If Not Proc1 Then Exit Sub End If If Not Proc2 Then Exit Sub End If Debug.Print "Done" End Sub Function Proc1() As Boolean Dim matchVal As Ssortingng matchVal = "A" Proc1 = IIf(Range("A1") = matchVal, True, False) End Function Function Proc2() As Boolean Dim matchVal As Ssortingng matchVal = "B" Proc2 = IIf(Range("B1") = matchVal, True, False) End Function 

Chaque fonction renvoie un boolean, c'est-à-dire vrai | Faux. Utilisez ceci pour tester le succès et quitter le sous si non.

Vous pouvez utiliser une variable globale comme suit:

 Public IsExit As Boolean Sub Proc1() 'your stuff here IsExit = True End Sub Sub Gom() IsExit = False Call Proc1 If IsExit Then Exit Sub Call Proc2 If IsExit Then Exit Sub Call Proc3 If IsExit Then Exit Sub Call Proc4 End Sub