Excel VBA Tutorial Part 1 - VBA Code Presentation
CommentsThe single most important practice for writing clear, decipherable code is to add frequent comments.Comments are lines in your code which act as notes to yourself or others, to explain what the code means or what it is doing. Comments are not executed during the running of the program, so have no impact on the result your macro. VBA considers any line that starts with an apostraphe (') to be a comment and the Excel VBA editor highlights these lines by colouring them in green, so you can see, at a glance, that they are comments and will not be executed. See the example below, which shows comments used to clarify the details of a simple subroutine:
Don't worry if you don't understand some of the code in the example above - this will be explained later in this tutorial. The example has been included simply to show how comments are used to to explain what each section of the code is for. It is easy to get lazy about adding comments to your code, but it really is worth making the effort. - the minutes invested in ensuring your code is well commented could save you hours of frustration in the long run! Code IndentationAnother way of assisting in making your code readable is by adding indentations to it. VBA code is generally indented inside Functions, Subroutines, If blocks or Loops. These indented sections enable you to easily see where each block of code starts and ends. If you look at the code block above (in the previous 'Comments' section), you will see how the indentations highlight where the 'For' Loop and the 'If' blocks start and begin.The Excel VBA editor helps you by automatically inserting indentations into certain parts of code, but you may sometimes need to add further indentations when you are editing your code. Line BreaksYour code can also be made more readable and easier to work with by inserting line breaks in the middle of long lines of code. In VBA, if you are going to split a line up, you need to add a space followed by an underscore ( _) just before the line break. This tells the VBA compiler that the current line of code continues on the following line.The following example shows how simple line breaks can be used to make long lines of code much easier to read and understand. Consider the following line of code:
If (index = 1 And sColor1 = "red") Or
(index = 2 And sColor1 = "blue") Or
(index = 3 And sColor1 = "green") Or
(index = 4 And sColor1 = "brown") Then
By adding line breaks the code can be presented as follows:
If (index = 1 And sColor1 = "red") Or _
(index = 2 And sColor1 = "blue") Or _ (index = 3 And sColor1 = "green") Or _ (index = 4 And sColor1 = "brown") Then The above presentation enables you to see the different conditions within the 'If' statement much more clearly and will therefore assist you in producing, and maintaining, effective bug-free code. |
||||
|
|
||||
Copyright © 2008-2010 ExcelFunctions.net |
