Ravindra Bagale · Excelसर्व coursesया course चे lessonsशोधाEnglish

Excel · मराठी आवृत्ती

12.14 On Error आणि cleanup

रवींद्र बागले यांच्या course वर आधारित · सहज मराठीत explanation

या page मध्ये

Expected bad input आधी validate करा; अनपेक्षित runtime errorसाठी handler ठेवा. Error लपवणं आणि हाताळणं वेगळं आहे.

Sub SafeCityReport()
    Dim ws As Worksheet
    Dim city As String
    Dim sales As Double, orders As Long

    On Error GoTo ErrHandler
    Application.ScreenUpdating = False

    Set ws = ThisWorkbook.Worksheets("Orders")     ' error 9 if the sheet is missing
    city = InputBox("City name:", "City report", "Pune")
    If city = "" Then GoTo CleanExit

    orders = Application.WorksheetFunction.CountIfs(ws.Range("C:C"), city)
    sales = Application.WorksheetFunction.SumIfs(ws.Range("G:G"), ws.Range("C:C"), city)
    MsgBox city & ": sales Rs " & Format(sales, "#,##0") & ", AOV Rs " & Format(sales / orders, "0.00")

CleanExit:
    Application.ScreenUpdating = True
    Exit Sub

ErrHandler:
    MsgBox "Error " & Err.Number & ": " & Err.Description, vbCritical, "SafeCityReport"
    Resume CleanExit
End Sub

हा source example missing Orders sheet किंवा division failure handlerमध्ये आणतो. पण unknown Cityसाठी orders=0 असल्यास divisionच्या आधी स्पष्ट message देऊन CleanExitला जा. 0/0 किंवा nonzero/0चा exact error codeवर logic बांधण्याऐवजी denominator तपासा.

Statementअर्थ
On Error GoTo LabelError handler सक्रिय करा.
On Error Resume NextErrorनंतरची line चालू ठेवा; Err तपासा.
On Error GoTo 0Current procedureचा handler बंद करा.
Err.Number / Err.DescriptionErrorची माहिती.
Resume LabelHandlerमधून ठरलेल्या labelकडे resume.

Settings restore करा

Source code ScreenUpdating शेवटी True करतो. Reusable macroमध्ये आधीच False असू शकतो; म्हणून original state जपून restore करा:

Dim previousScreen As Boolean, previousAlerts As Boolean
previousScreen = Application.ScreenUpdating
previousAlerts = Application.DisplayAlerts
' ... main work with an error handler ...
' In the shared cleanup path:
Application.DisplayAlerts = previousAlerts
Application.ScreenUpdating = previousScreen

हा cleanup patternचा अंश आहे, स्वतंत्र पूर्ण Sub नाही. Events/Calculation बदलल्यास त्यांचाही original state restore करा. Source comments/messagesमध्ये Rs वापरलं आहे; VBEची Unicode handling मर्यादित असू शकते, rupeeसाठी ChrW(8377) वापरता येतो.

Practice

Split utilityला common cleanup path द्या. Missing source, invalid sheet name आणि zero rowsवर friendly message व restored settings तपासा. Existing sheet deletion टाळणारा output design वापरा.