Comment utiliser l’instruction Exit dans VBA ?

L’instruction `Exit` en VBA (Visual Basic for Applications) est utilisée pour quitter prématurément une structure de contrôle, telle qu’une boucle ou une procédure. Voici comment l’utiliser dans différents contextes :

   Sub ExempleSub()
       Dim i As Integer
       For i = 1 To 10
           If i = 5 Then
               Exit Sub
           End If
       Next i
       MsgBox "Ceci ne s'affichera pas si i atteint 5."
   End Sub
   Function ExempleFunction() As Integer
       Dim i As Integer
       For i = 1 To 10
           If i = 5 Then
               ExempleFunction = i
               Exit Function
           End If
       Next i
       ExempleFunction = -1 ' Ceci ne sera pas atteint si i est 5
   End Function
   Sub ExempleFor()
       Dim i As Integer
       For i = 1 To 10
           If i = 5 Then
               Exit For
           End If
           Debug.Print i
       Next i
       MsgBox "Boucle For terminée."
   End Sub
   Sub ExempleDo()
       Dim i As Integer
       i = 1
       Do While i <= 10
           If i = 5 Then
               Exit Do
           End If
           Debug.Print i
           i = i + 1
       Loop
       MsgBox "Boucle Do terminée."
   End Sub
  • Exit Sub : Utilisée pour sortir d’une procédure Sub avant d’atteindre la fin de celle-ci.
  • Exit Function : Utilisée pour quitter une fonction avant la fin. Cela arrête l’exécution de la fonction et renvoie le contrôle au code appelant.
  • Exit For : Utilisée pour sortir d’une boucle `For` avant qu’elle ne soit terminée.
  • Exit Do : Utilisée pour quitter une boucle `Do` avant qu’elle ne soit terminée.
  • Exit While : Not directly supported, but you can use `Exit Do` inside a `Do While` loop, which effectively serves the same purpose since VBA doesn’t have a native `While` loop construct like some other languages.

Ces instructions `Exit` sont pratiques lorsque vous devez sauvegarder des ressources ou éviter des traitements inutiles dès que certaines conditions sont remplies.

Unlock Your Potential

Excel

Basic - Advanced

Access

Access Basic - Advanced

Power BI

Power BI Basic - Advanced

Help us grow the project