VBA/Excel/Access/Word/Language Basics/Exit — различия между версиями

Материал из VB Эксперт
Перейти к: навигация, поиск
м (1 версия)
 
м (1 версия)
 
(нет различий)

Текущая версия на 12:46, 26 мая 2010

A Generic Procedure Skeleton with Basic Error Handling

 
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



Exiting a For...Next Loop Early

 
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



Using an Exit Do Statement

 
 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