Trapping Script Errors

All script errors, whether they are compile-time or runtime errors, will cause the Error event to be triggered. In Listing 13.8, I handle both types of errors. Unlike the error handling in the MSScript Demo program (Listing 13.5), here I help the user identify and correct the error in a more user-friendly fashion.

Listing 13.8: ScriptControl1_Error Event in Programmable Calculator

Private Sub ScriptControl1_Error()
Dim i As Integer
Dim k As Integer
If SSTab1.Tab <> 1 Then
   SSTab1.Tab = 1
   CodeBlock.Text = Code(CurrentButton)
End If
k = 1
For i = 1 To ScriptControl1.Error.Line - 1
   k = InStr(k, CodeBlock.Text, vbCrLf)
Next i
CodeBlock.SetFocus
CodeBlock.SelStart = k + 2 + ScriptControl1.Error.Column
k = InStr(CodeBlock.SelStart, CodeBlock.Text, vbCrLf)
CodeBlock.SelLength = k - CodeBlock.SelStart
StatusBar1.Panels(1).Text = ScriptControl1.Error.Description
ScriptControl1.Reset
Beep
End Sub

I begin the routine by seeing if the Code View tab is already visible. If it is not, then I make it visible and load the code related to the current button. Next, I use a For/Next loop to find the line containing the error. I scan the text box looking for carriage return/line feed pairs (vbCrLf). Since each line ends with a carriage return/line feed pair, I look for the line before the error, knowing that two characters after that is the start of the line I want.

Once I have the character offset to the start of the line with the error, I can find the starting position of the error by simply adding the Error object’s Column property. By setting the text box’s SelStart property, the cursor will be placed in front of that character. Then I can highlight the rest of the line of code by setting the SelLength property to the number of characters left in the line. I do this by searching for the position of the next carriage return/line feed pair and subtracting the current value of the SelStart property.

I finish this routine by copying the error’s description into the status bar. Then I clear the error condition by using the Reset method. Finally, I provide a multimedia beep to let the user know something isn’t right.

© 1998 SYBEX Inc. All rights reserved.