|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer|
A statement in Visual Basic is a complete instruction. It can contain keywords, operators, variables, constants, and expressions. Each statement belongs to one of the following categories:
Declaration Statements, which name a variable, constant, or procedure, and can also specify a data type.
Executable Statements, which initiate actions. These statements can call a method or function, and they can loop or branch through blocks of code. Executable statements include Assignment Statements, which assign a value or expression to a variable or constant.
Putting Multiple Statements on One Line
You can have multiple statements on a single line separated by the colon (:) character. The following example illustrates this.
Though occasionally convenient, this form of syntax makes your code hard to read and maintain. Thus, it is recommended that you keep one statement to a line.
Continuing a Statement over Multiple Lines
A statement usually fits on one line, but when it is too long, you can continue it onto the next line using a line-continuation sequence, which consists of a space followed by an underscore character (_) followed by a carriage return. In the following example, the MsgBox executable statement is continued over two lines.
Source code is not always self-explanatory, even to the programmer who wrote it. To help document their code, therefore, most programmers make liberal use of embedded comments. Comments in code can explain a procedure or a particular instruction to anyone reading or working with it later. Visual Basic ignores comments during compilation, and they do not affect the compiled code.
Comment lines begin with an apostrophe (') or REM followed by a space. They can be added anywhere in code, except within a string. To append a comment to a statement, insert an apostrophe or REM after the statement, followed by the comment. Comments can also go on their own separate line. The following example demonstrates these possibilities.
Checking Compilation Errors
If, after you type a line of code, the line is displayed with a wavy blue underline (an error message may appear as well), there is a syntax error in the statement. You must find out what is wrong with the statement (by looking in the task list, or hovering over the error with the mouse pointer and reading the error message) and correct it. Until you have fixed all syntax errors in your code, your program will fail to compile correctly.