1 / 40

CST-273-01 Microsoft VBA R. Juhl

CST-273-01 Microsoft VBA R. Juhl. Trapping Errors and Debugging Code . Trapping Errors and Debugging Code . Programming errors can vary by … Type Cause Effect Severity Other factors Error types Include Syntax Logic Compile Run-time Semantic. Trapping Errors and Debugging Code .

reuel
Download Presentation

CST-273-01 Microsoft VBA R. Juhl

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CST-273-01Microsoft VBAR. Juhl Trapping Errors and Debugging Code

  2. Trapping Errors and Debugging Code • Programming errors can vary by … • Type • Cause • Effect • Severity • Other factors • Error types Include • Syntax • Logic • Compile • Run-time • Semantic

  3. Trapping Errors and Debugging Code • Syntax Errors • Easy to avoid • Sometimes Difficult to find • MySpecialVariable • MySpecialVaraible • Adding Option Explicit to the beginning of • Modules • Forms • ….can eliminate most of these types of errors • Why?

  4. Trapping Errors and Debugging Code • Syntax Errors • Use the IDE balloon help • To Provide context sensitive help • If one does not appear……. • When typing a function name • Indicates a problem • You can look at code for hours and not see them • Syntax Errors can produce logic errors • Your program may not complain about a new variable that you intended to be a declared variable ….. with a slightly different name. • Your indented variable may not get updated

  5. Trapping Errors and Debugging Code • Logic Errors • Your code produces incorrect results • VBA compiler may not complain but the results may cause • Quirky results • Incorrect results • Run-time errors ( infinite loop ) • Compile Errors • VBA compiler is actually a syntax checker • VBA compiler does not produce a free standing module or executable • The compiler runs constantly and looks for errors • If –then statement without an end if produces an error immediately

  6. Trapping Errors and Debugging Code • Compiler Errors • Compiler checks • Syntax • Missing elements • Punctuation Errors (missing periods commas etc.) • Adding Option explicit will find data type mismatches at run time Dim num As Integer num = “string” • Is allowed until runtime • Error: Run time error 13 type mismatch

  7. Trapping Errors and Debugging Code • Run time errors • Happens when something outside your program is incorrect. • A disk access request can fail • You could type the wrong information • Will Cause your program to crash • Divide by zero • File not found • Cannot be fixed by altering the logic of the program • The program may require error handling routines • Code • Procedures

  8. Trapping Errors and Debugging Code

  9. Trapping Errors and Debugging Code Sub test() Dim num As Integer On Error GoTo exception num = "hi" MsgBox ("The value of num is " & num) Exit Sub exception: MsgBox ("type mismatch") num = 0 Resume Next End Sub Link to file

  10. Trapping Errors and Debugging Code • Run time errors • Error handling code should be used whenever the program interacts with the user or other components of the computer • On Error GoTostatement • On Error GoToline Enables the error-handling routine that starts at line specified in the required line argument. The line argument is any line label or line number. If a run-time error occurs, control branches to line, making the error handler active. The specified line must be in the same procedure as the On Error statement; otherwise, a compile-time error occurs.

  11. Trapping Errors and Debugging Code

  12. Trapping Errors and Debugging Code Public Sub test() Dim num As Variant Dim div As Variant Dim quo As Variant On Error GoTo exception ‘on division by zero error goto the label called exception num = InputBox("enter the dividend") div = InputBox("enter the divisor") quo = num / div ‘ line of code that could generate a run time error / division by zero MsgBox (num & " / " & div & " = " & quo) ‘out put the results of division Exit Sub ‘ program ends here if no error is encountered exception: MsgBox ("division by zero is not allowed") ‘Generate a warning message div = InputBox("enter the divisor") ‘ line or lines of code that fix the error Resume ‘go back to the line that caused the error End Sub Link to code

  13. Trapping Errors and Debugging Code • Avoiding run-time errors • Check every input for data type, length, value and meaning Public Sub test() Dim num As Variant Dim div As Variant Dim quo As Variant num = InputBox("enter the dividend") div = InputBox("enter the divisor") ' Error handling code w/o the use of On Error Goto While (div = 0) If div = 0 Then MsgBox ("division by zero is not allowed") div = InputBox("enter the divisor") End If Wend 'end of error handling quo = num / div MsgBox (num & " / " & div & " = " & quo) End Sub

  14. Trapping Errors and Debugging Code • Avoiding run time errors……continued • Provide easy to understand prompts for your application • Make the prompts and error messages as specific as possible • Offer to fix the problem automatically whenever possible • Offer to retry the operation after you correct the error • Reduce the chances of error by providing context sensitive help

  15. Trapping Errors and Debugging Code • Recovering from an error • Adding recovery code means that you can count on your program to help you overcome problems with the system and keep your data safe. • Two kinds of recovery code • Code that recovers before the error happens • Code that recovers after the error happens • Common runtime error is running out of disk space • Adding a drive checking feature • Add a new library to your program • Use Tools  References Command to display the references dialog box

  16. Trapping Errors and Debugging Code

  17. Trapping Errors and Debugging Code Public Sub DriveTest() ' Create a variable to hold the free space. Dim FreeSpace As Double 'changed from long as drives are larger ' Create a reference to the file system. Dim MyFileSystem As FileSystemObject ' Create a reference for the target drive. Dim MyDrive As Drive ' Create a dialog result variable. Dim Result As VbMsgBoxResult 'Provide a jump back point. DoCheckAgain: ' Fill these two objects with data so they show the ' available space on drive C. Set MyFileSystem = New FileSystemObject 'instantiate the fileSystemObject Set MyDrive = MyFileSystem.GetDrive("C") 'Set the GetDrive Property of the FSO Drive to C ' Determine the amount of free space. FreeSpace = MyDrive.AvailableSpace 'assign the AvailableSpace property value to FreeSpace

  18. Trapping Errors and Debugging Code ' Make the check. If FreeSpace < 100000000000 Then ' The drive doesn't have enough space. Ask what to ' do. Result = MsgBox("The drive doesn't have enough " + _ "space to hold the data. Do you" + _ " want to correct the error?" + _ vbCrLf + _ Format(FreeSpace, "###,###") + _ " bytes available, " + _ "1,000,000,000 bytes needed.", _ vbYesNo Or vbExclamation, _ "Drive Space Error")

  19. Trapping Errors and Debugging Code ' Determine if the user wants to correct the error. If Result = vbYes Then ' Wait for the user to fix the problem. MsgBox "Please click OK when you have freed" + _ " some disk space.", _ vbInformation Or vbOKOnly, _ "Retry Drive Check" ' Go to the fallback point. GoTo DoCheckAgain Else ' The user doesn't want to fix the error. MsgBox "The program can't save your data " + _ "until the drive has enough space.", _ vbInformation Or vbOKOnly, _ "Insufficient Drive Space" ' End the Sub. Exit Sub End If End If End Sub

  20. Trapping Errors and Debugging Code Folder not found……………………Possible code Sub test4() Dim fso As New FileSystemObject 'create fso object variable Dim flds As Folders 'create f object variable Dim strText As String 'string var Dim i As Integer 'index var 'get folder method of fso returns a folder object corresponding to the folder in a specified path in this case ‘the folderspec is E:\ 'Subfolder Property Returns a Folders collection consisting of all folders contained in a specified 'folder, including those with Hidden and System file attributes set. Set flds = fso.GetFolder("e:\").SubFolders i = 1 'for every folder in the collection create a string that includes the path and size 'output the results to successive cells in worksheets("sheet1") For Each f In flds strText = f.Path & " - " & f.Size Worksheets("Sheet1").Cells(i, 1) = strText i = i + 1 Next End Sub

  21. Trapping Errors and Debugging Code

  22. Trapping Errors and Debugging Code • Symantic Errors • VBA Code and Logic are correct • The meaning behind the code isn’t what was intended • You used a Do Until loop when you needed a Do While loop

  23. Trapping Errors and Debugging Code • Symantic Errors • VBA Code and Logic are correct • The meaning behind the code isn’t what was intended • You used a Do Until loop when you needed a Do While loop • What is the difference ?

  24. Trapping Errors and Debugging Code Public Sub test() Dim i As Integer Dim s1 As String Dim s2 As String Do Until (i < 20) 'Do until false s1 = s1 & i & " " i = i + 1 Loop MsgBox ("Do Until Loop: " & s1) WHAT IS THE OUTPUT FROM THIS CODE ? Do While (i < 20) 'Do while true s2 = s2 & i & " " i = i + 1 Loop MsgBox ("Do While Loop: " & s2) End Sub

  25. Trapping Errors and Debugging Code • More Error Handling Public Sub ErrorHandle() ' The variable that receives the input. Dim InNumber As Byte ‘will not allow a letter or special char ' Tell VBA about the error handler. On Error GoToMyHandler ' Ask the user for some input. InNumber = InputBox("Type a number between 1 and " + _ "10.", "Numberic Input", "1")

  26. Trapping Errors and Debugging Code ' Determine whether the input is correct. If (InNumber < 1) Or (InNumber > 10) Then ' If the input is incorrect, then raise an error. Err.RaisevbObjectError + 1, _ "ErrorCheck.ErrorCondition.ErrorHandle", _ "Incorrect Numeric Input. The number " + _ "must be between 1 and 10." Else ' Otherwise, display the result. MsgBox "The Number You Typed: " + CStr(InNumber), _ vbOKOnly Or vbInformation, _ "Successful Input" End If ' Exit the Sub. Exit Sub

  27. Trapping Errors and Debugging Code ' The start of the error handler. MyHandler: ' Display an error message box. MsgBox "The program experienced an error." + vbCrLf + _ "Error Number: " + CStr(Err.Number) + vbCrLf + _ "Description: " + Err.Description + vbCrLf + _ "Source: " + Err.Source, _ vbOKOnly Or vbExclamation, _ "Program Error" ' Always clear the error after you process it. Err.Clear End Sub

  28. Trapping Errors and Debugging Code • Err Object • Contains information about run-time errors. • Remarks • The properties of the Err object are set by the generator of an error — Visual Basic, an object, or the programmer. • The default property of the Err object is Number. Because the default property can be represented by the object name Err, earlier code written using the Err function or Err statement doesn't have to be modified. • When a run-time error occurs, the properties of the Err object are filled with information that uniquely identifies the error and information that can be used to handle it. To generate a run-time error in your code, use the Raise method. • The Err object's properties are reset to zero or zero-length strings ("") after an Exit Sub, Exit Function, Exit Property or Resume Next statement within an error-handling routine. Using any form of the Resume statement outside of an error-handling routine will not reset the Err object's properties. The Clear method can be used to explicitly reset Err. • Use the Raise method, rather than the Error statement, to generate run-time errors for system errors and class modules. Using the Raise method in other code depends on the richness of the information you want to return. • The Err object is an intrinsic object with global scope. There is no need to create an instance of it in your code.

  29. Trapping Errors and Debugging Code • Raise Method • Generates a run-time error message • Syntax: object.Raise number, source, description, helpfile, helpcontext • User with the Err object (Err.raise) • The error number can be custom by adding a number to the default value of the vbObjectError • Note that the constant vbObjectError is a very large negative number

  30. Trapping Errors and Debugging Code • Never use the On Error GoTo0 • This statement turns off error handling • Can cause a range of problems including • Application failure • Data loss • Reporting errors • Message Box • Text File (chapter 10) • E-Mail (chapter 16)

  31. Trapping Errors and Debugging Code • Export file (Right click module, form, etc.)

  32. Trapping Errors and Debugging Code • Import files (form, basic , class) (r-click project explorer)

  33. Trapping Errors and Debugging Code • Built in Debugger • Add by right clicking on the IDE menu and selecting Debug • Set a breakpoint in your code by using the Breakpoint icon or double clicking the line • The program halts at that point • Debug your code By using • Locals • Watch • Breakpoints • You can use run with breakpoints and / or F8 to step into your code line by line • Step over used to see effects of statements in the current module. • Called subs functions still execute but you do not see them line by line

  34. Trapping Errors and Debugging Code

  35. Trapping Errors and Debugging Code

  36. Trapping Errors and Debugging Code

  37. Trapping Errors and Debugging Code

  38. Trapping Errors and Debugging Code

  39. Trapping Errors and Debugging Code

  40. Trapping Errors and Debugging Code

More Related