Mistakes are a fact of life, and Visual Basic is fairly intolerant of them. If you followed along with the preceding lab, you probably already encountered that fact. Sometimes it’s pretty easy to tell what you’ve done wrong, and sometimes it’s almost impossible—even for experienced programmers! What marks the difference between beginning and expert programmers is how they go about solving those problems.
To help you understand fixing mistakes, you need to know that there are four different kinds of errors that are generally identified by where or why they happen:
Occur when you mistype a statement, such as omitting a closing parenthesis or omitting some part of the statement that is required. Visual Basic detects these errors right away and highlights them in red as soon as you move to the next line of code.
Are also often the result of a typo, but they appear valid to Visual Basic as you type. Examples of this kind of error include misspelling a method or property name or using a variable or procedure name that isn’t defined yet. Visual Basic checks for these errors the moment you run your code (for instance, when you press F5). At that point, Visual Basic converts your code into a form that Excel understands (this is called compiling), and if any of the names you used aren’t found, compiling stops and Visual Basic highlights the error. Semantic errors are sometimes called compile-time errors for that reason.
Can be the hardest to detect. These errors occur when your code simply doesn’t do what you expected it to do. Infinite loops (lather, rinse, repeat...) are an example, as are unexpected results such as formatting code that doesn’t format everything it should. Logic errors can sometimes halt your code while it is running, and for that reason they are often called runtime errors .
Aren’t your fault, but you need to deal with them all the same. These are another type of runtime error, and they are usually the result of using resources outside of Excel, such as trying to get a file from disk or trying to connect to a database somewhere. In those cases, you need to anticipate the possibility of a problem using a technique called exception handling (which I cover in Chapter 2).