VBA/Excel/Access/Word/Language Basics/Exit
A Generic Procedure Skeleton with Basic Error Handling
<source lang="vb">
Sub GenericProcedure()
On Error GoTo ErrHandler Exit Sub
ErrHandler:
MsgBox "An error has occurred. " & _ Err.Number & ": " & Err.Description _ , vbInformation + vbOKOnly, "An Error has occurred." Debug.Print "ERROR OCCURED IN GenericProcedure..." Debug.Print Err.Number & ": " & Err.Description
End Sub
</source>
Exiting a For...Next Loop Early
<source lang="vb">
Sub ExitForExample()
Dim nLastRow As Integer Dim nColumn As Integer Dim nRow As Integer Dim ws As Worksheet Set ws = ThisWorkbook.Worksheets(1) nLastRow = 15 nColumn = 1 For nRow = 1 To nLastRow If ws.Cells(nRow, nColumn).Address = "$A$7" Then Debug.Print "Found cell. Exiting for loop." Exit For Else Debug.Print ws.Cells(nRow, nColumn).Address End If Next Set ws = Nothing
End Sub
</source>
Using an Exit Do Statement
<source lang="vb"> Sub Lottery_2() Dim sngWin As Single Do Until sngWin > 2000 sngWin = Rnd * 2100 If sngWin < 500 Then Debug.Print "less than 500" Exit Do End If Debug.Print sngWin Loop End Sub </source>