VBA programming consists of writing statements and comments. While comments are not explicitly required, uncommented code is hard to read and very difficult to understand, especially if someone else needs to work with your code. When working with the VBA Editor in Access, comments are prefaced with an apostrophe and appear in green. Comments are ignored during code execution. You can have one or many lines of comments in a procedure, and VBA will ignore them all. Comments don't slow down the execution of your code; so don't be afraid to use them liberally. At a minimum, your comments should list what the procedure is for and when it was written. Figure 4.2 shows a typical procedure with detailed comments.
<31 Microsoft Visual Basic - VBA Samples - [Samples (Code)]
Project - VBA Samples
É [£vO Microsoft Office Access Ciass Objects H-Ê3 Modules
Module! iil:^ Samples
Run lools Add-lns Window Help Type a question for help - - ri X
Properties - Samples
I Samples Module Alphabetic | Categorized |
^ I J GoShoppingSuits
Private Sub GoShoppingSuits ()
1 This procedure lets the user calculate the number
'of suits they can buy and still stay within their budget
1 Procedure by Patricia Cardosa on 10/20/03
Dim intSuits As Integer Dim cur Suit-Price As Currency Dim curTotalPrice As Currency Dim i As Integer
'Define the current suit price curSuitPrice = 100
'Ask the user how many suits they need intSuits = InputBox("Enter the desired number of suits", "Sui
'Loop once for every suit the user wants to buy
For i = 1 To intSuits curTotalPrice = curTotalPrice + curSuitPrice If curTotalPrice > curBudget Then blnOverBudget = True
Else blnUnderBudget = False ifsjiLJ _ _if1
You might be wondering why you need to add comments to code you're writing for your own applications. Well, any time you write code, there's a chance that code will be used for more than one application. It's also possible that someone else will eventually inherit your code. What if you choose to leave your current position to take a new job? When your company hires a replacement programmer, they might need to make changes to your code. If you haven't added any comments to your code, they might have a hard time understanding your procedures. If you've ever had to examine another programmer's code and found it without comments, you'll understand the importance of comments.
Comments also help you understand why you might have used a particular piece of code. For example, if you hard coded certain values within your application, you might wonder why you chose to use those particular values. You can use comments to remind yourself why you used specific code.
Was this article helpful?