Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in On Error statement

Tags:

vbscript

I am totally not a VBScript developer. But as it usually happens I have to write a small script to check something. It opens Excel, writes something to it and closes it. But that's not the point. The point is that I cannot manage to write code for error handling. This script:

Sub Work()
On Error GoTo ErrMyErrorHandler
Dim objExcelApp
Dim wb
Dim ws

Set objExcelApp = CreateObject("Excel.Application")
Set wb = objExcelApp.Workbooks.Add(True)
Set ws = wb.Sheets(1)

ws.Cells(1,1).Value = "Hello"
ws.Cells(1,2).Value = "World"

wb.SaveAs("c:\test.xls")
objExcelApp.Quit()
Exit Sub

ErrMyErrorHandler:
MsgBox Err.Description, vbExclamation + vbOKCancel, "Error: " & CStr(Err.Number)    
End Sub

Work()

gives this error:

error

Line 2 is the line with the On Error statement. What am I doing wrong?

Thank you.

like image 897
Grigory Avatar asked Feb 23 '23 18:02

Grigory


2 Answers

looks like you can not point custom label to error handler in VB Script. You can only use

on error goto 0 '(raises exceptions)
on error resume next '(ignores exceptions)

if you use the second syntax, you can catch occurring exceptions via Err global variable:

  if Err.Number <> 0 then MsgBox "Exception occurred: " & Err.Description
like image 159
heximal Avatar answered Mar 07 '23 11:03

heximal


Heximal is correct that VBScript does not allow custom labels for error handlers. Using your example, you'd really be trying to do something like this.

Sub Work
    On Error Resume Next

    Dim objExcelApp
    Dim wb
    Dim ws

    Set objExcelApp = CreateObject("Excel.Application")
    Set wb = objExcelApp.Workbooks.Add(True)
    Set ws = wb.Sheets(1)

    ws.Cells(1,1).Value = "Hello"
    ws.Cells(1,2).Value = "World"

    wb.SaveAs("c:\test.xls")
    objExcelApp.Quit()

    If Err.Number <> 0 Then ErrMyErrorHandler
End Sub

Sub ErrMyErrorHandler
    MsgBox Err.Description, vbExclamation + vbOKCancel, "Error: " & CStr(Err.Number)
End Sub

Work()

But you should really understand that this is not the most wisely constructed code. You should perform error checks at EVERY relevant spot and and handle them individually as necessary. If your are looking for a full-scale error handling solution then you need to understand more about how VBScript works internally. Take a look at the following link.

Error Trapping and Capturing Third-Party Output in VBScript

like image 33
Nilpo Avatar answered Mar 07 '23 11:03

Nilpo