Share via


Formatting Code

Some developers believe that although formatting code might make it look pretty, it is not really worth the time. However, properly formatting code has nothing to do with appearance and everything to do with how easy your code is to understand and maintain. The basic techniques used to format code are line breaks, white space, and indentation. In addition to making the code easier to read, these formatting techniques help document the code by showing the logic and flow of a procedure and by grouping logically related sections of code.

Formatting VBScript vs. VBA Code

Even developers of the most feebly written Microsoft® Visual Basic® for Applications (VBA) code usually attempt to name things consistently and add comments and perhaps some white space where appropriate. However, something very different is happening on the Web. It seems there is no attempt to use naming conventions or formatting techniques to make script easier to understand and maintain; in fact, just the opposite appears to be happening. Perhaps it is the forgiving nature of an HTML page as a scripting environment, or perhaps it is because script in an HTML page is viewed easily by others, and the easier it is to understand, the easier it is for someone to borrow.

Line Breaks

In VBA and Visual Basic Scripting Edition (VBScript) code, you break a line by using the line-continuation character — an underscore (_) preceded by a space. You use line breaks to make sure that your code does not extend beyond the right edge of the Code window (usually about 60 characters).

For example, line breaks have been used in the following code, so the entire string can be viewed in the Code window without having to scroll to the right:

Dim strMessage As String
strMessage = "Fourscore and seven years ago our fathers " _
   & "brought forth, on this continent, a new nation, " _
   & "conceived in liberty, and dedicated to the " _
   & "proposition that all men are created equal."
MsgBox strMessage

Note how an additional tab character is inserted for all lines following the initial line break. This creates the visual cue that the indented text remains a part of the portion of the string that comes before the line break.

If the line following the continued line is indented as much as the continued line would be, add one more tab to the continued line to distinguish it from the next line. For example:

If ActiveSheet.ChartObjects(1).Chart.ChartTitle = _
      ActiveSheet.Range("a2").Value Then
   MsgBox "They are equal."
End If

Be careful when you are using line-continuation characters in strings. If you must divide the string into two or more strings, place the line-continuation character between the strings, and then concatenate them using the ampersand (&). It is important to preserve all spaces in the string when it is concatenated. For example:

Sub LongString()
   ' This will form a correct SQL string.
   strSQL = "SELECT LastName, FirstName FROM Employees WHERE " _
      & "(BirthDate > #1-1-60#);"

   ' This one will be missing the space between WHERE and (BirthDate).
   strSQL = "SELECT LastName, FirstName FROM Employees WHERE" _
      & "(BirthDate > #1-1-60#);"
End Sub

Use the ampersand (&) for all concatenation operations; never use the plus sign (+).

In HTML code, you create a line break by entering a carriage return. The browser will ignore these line breaks when it renders the page. For example, text in this HTML page will break only where the <BR> element appears:

<BODY>
   <CENTER>
   <H2>Office Programmer's Guide 
   <BR>Programming Concepts 
   <BR>HTML Sample Page: Line Breaks</H2>
   <HR>
   <H3>To see an example, click Source 
   on the View menu.</H3>
   <BR>
   <BR>
   </CENTER>

   Fourscore and seven 
   years ago our fathers 
   brought forth, on this 
   continent, a new nation, 
   conceived in liberty, and 
   dedicated to the proposition 
   that all men are created equal. 

</BODY>

White Space

Use blank lines to separate logically related blocks of code, introductory (header) comments from the first variable declaration, and the last declared variable from the code itself. Precede all comments with a blank line.

Indentation

Indent code and comments within a procedure by using a two- to four-space tab stop. (The Visual Basic Editor uses a four-space tab stop by default.) As with white space, indents are used to organize code logically and make it visually appealing.

The following list contains some general guidelines regarding where, when, and how to use indentation correctly to make your code more readable and maintainable:

  • Indent all code and comments within a procedure at least one tab stop. The only code lines that are not indented are the beginning and ending of the procedure and line labels used in connection with your error handler.
  • If you use line breaks to format a procedure's argument list, use tabs to indent the arguments and their data-type declarations, so they are aligned with the first argument in the list.
  • Indent declared variables one tab stop. Declare only one variable on a line.
  • Indent control structures at least one tab stop. If one control structure is embedded within another, indent the embedded structure one tab stop. Indent code within a control structure one additional tab stop.
  • If you use a line-continuation character to break a line of code, indent the new line one extra tab stop. This creates a visual cue that the two (or more) lines belong together. If the line following the continued line is indented as much as the continued line would be, add one more tab to the continued line to distinguish it from the next line.
  • Indent comments to the same level as the code to which the comment refers.

Look at how these general techniques are applied in the following procedure:

Function GetFileList(strDirPath As String, _
                     Optional strFileSpec As String = "*.*", _
                     Optional strDelim As String = ",") As String
   
   ' This procedure returns a delimited list of files from the
   ' strDirPath directory that match the strFileSpec argument.
   ' The default delimiter character is a comma. By default, the
   ' procedure returns all files ("*.*") from the designated
   ' directory.
      
   Dim strFileList      As String ' Used to collect the file list.
   Dim strFileNames   As String ' The full path and criteria to search for.
   Dim strTemp         As String ' Temporarily holds the matching file name.
   
   ' Make sure that strDirPath ends in a "\" character.
   If Right$(strDirPath, 1) <> "\" Then
      strDirPath = strDirPath & "\"
   End If
   
   ' This will be our file search criteria.
   strFileNames = strDirPath & strFileSpec
   
   ' Create a list of matching files delimited by the
   ' strDelim character.
   strTemp = Dir$(strFileNames)
   Do While Len(strTemp) <> 0
      strFileList = strFileList & strTemp & strDelim
      strTemp = Dir$()
   Loop
   
   If Len(strFileList) > 1 Then
      ' If there are matching files, remove the delimiter
      ' character from the end of the list.
      GetFileList = Left(strFileList, Len(strFileList) - 1)
   Else
      GetFileList = ""
   End If
End Function

See Also

Structuring and Formatting Your Code | Structuring Your Code | Using Web Technologies