Tip Program Bugs

You've probably heard more than once that "computer programs are full of bugs." In programming, errors are called bugs, and debugging is the process of eliminating errors from your programs. The first step in debugging a procedure is to correct all syntax errors. Visual Basic provides a myriad of tools with which to track down and eliminate bugs. In this chapter, you will find out how you can use Visual Basic's assistance in writing code with a minimum amount of errors. In Chapter 13, you will learn how to use special debugging tools to trap errors in your VBA procedures.

In addition to syntax errors, there are two other types of errors: run-time and logic. Run-time errors occur while the procedure is running. A typical


j-J |W1iflslnACell

Sub WhatsinACellQ

"What sin AC el I Macro "Macro recorded5/31/2002 by Julilta Korol ' Indicates the contents of the underlying cells: text, numbers, ' formulas_

Microsoft Visual Basic

Compile error:

Expected end tA statement


.Subscript = Fatse .OuttlrteFonl = False Shadow = False

.Uncferline = xl IJ nd erlin e 5t y I eNo rte Colodndex = 13 End With

Range("B6") Select

Sele ct io rt. 5 pe c i a IC ell SXICe in~y pe C on sta rit &, I fl. Se le ct With Select ion. Font .Name = "Arial"

Figure 2-8:

This error message was caused by a missing beginning parenthesis in front of xlCellType-Constants.

run-time error is shown in Figure 2-9. Run-time errors are often caused by those unexpected situations that the programmer did not think of while writing the code. These occur, for example, when the program is trying to access a drive or a file that does not exist on a user's computer or copy a file to a floppy disk without first checking whether the user had inserted a floppy disk and closed the drive door.


Sub WhatsinACellQ

' WhatslnACell Macro

' Macro recorded 5/31/2002 by Jul ¬°It a Korol

' Indicates the contents of lhe underlying cells: text, numbers,


Selection Sp ecia IC el Is (*l C ellTy peC onsta nt s. 2), Select

Microsoft Visual Basic

Run-time error '1004':

No cells were foind.

End 1

1 : Debug :]



Se le et i on. Sp ecia IC el Is (* IC ellTy peC onsta ni s, 1 ). S e I ect With Selection.Font Name = "Arial"

Se le et i on. Sp ecia IC el Is (* IC ellTy peC onsta ni s, 1 ). S e I ect With Selection.Font Name = "Arial"

Figure 2-9: When Visual Basic tries to select text cells when none exist in the selected worksheet or range of cells, a run-time error occurs.

The third type of error, logic error, often does not generate a specific error message. The procedure may have no flaws in its syntax and may even run without errors, yet it produces incorrect results. Logic errors are usually very difficult to locate, and those that happen intermittently are so well-concealed that you can count on spending long hours, and even days, trying to locate the source of the error.

0 0

Post a comment