|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|
Breaking and Combining Statements in Code
When writing your code, you may at times create lengthy statements that necessitate horizontal scrolling in the Code Editor. While this does not affect the way your code runs, it makes it difficult for you or anyone else to read the code as it appears on the monitor. In such cases, you should consider breaking the single long statement into several lines.
At other times, you may want to consolidate statements on a single line; for instance, when you have several very short statements and want to conserve space. This feature can also be handy when organizing variables or commands within a module.
To break a single statement into multiple lines
- Use the line-continuation sequence, which is a space followed by an underscore ( _), at the point at which you want the line to break. In the following example, the statement is broken into four lines with line-continuation sequences terminating all but the last line:
Data1.RecordSource = _ "SELECT * FROM Titles, Publishers" _ & "WHERE Publishers.PubId = Titles.PubID" _ & "AND Publishers.State = 'CA'"
Using this sequence makes your code easier to read, both online and when printed.
Note The line-continuation sequence is necessarily the last thing on a line. You cannot follow it with anything else on the same line.
Some limitations exist as to where the line-continuation sequence can be used, such as in the middle of an argument name. You can break an argument list with the line-continuation sequence, but the individual names of the arguments must remain intact.
Note You cannot continue a comment by using a line-continuation sequence. Once a comment begins, the compiler does not examine the characters for special meaning. For a multiple-line comment, repeat the comment symbol (') on each line.
While placing each statement on a separate line is the recommended method, Visual Basic also allows you to place multiple statements on the same line.
To place multiple statements on the same line
- Separate the statements with a colon (:), as in the following example:
Text1.Text = "Hello" : Red = 255 : Text1.BackColor = Red