Skip to Content
Course content

8.2. Commenting and Documenting Code

Commenting and documenting your code are essential practices in software development that significantly enhance the readability, maintainability, and collaborative potential of your code. In VBA (Visual Basic for Applications), clear comments help both you and other developers (or future you) understand what the code does and why certain decisions were made.

1. Why Comment and Document Code?

1.1. Improves Readability

  • Comments provide explanations for complex or non-obvious sections of code, making it easier for someone (or yourself) to understand the purpose and functionality at a glance.

1.2. Aids Debugging and Troubleshooting

  • Well-commented code helps you quickly identify where things went wrong during debugging by explaining the intent of specific code blocks.

1.3. Facilitates Collaboration

  • Comments make it easier for others to contribute to your project by explaining the logic, expected inputs, and outputs of different sections of your code.

1.4. Enhances Maintenance

  • As your code evolves or if someone else takes over maintenance, comments provide context that aids in making changes or updates without causing unintended issues.

2. Types of Comments in VBA

2.1. Single-Line Comments

  • Use single-line comments for brief explanations or notes about specific lines or blocks of code. Start a comment with an apostrophe (').
    • Example:
      ' Calculate the total price including tax
      totalPrice = price * 1.1
      

2.2. Multi-Line Comments

  • You can add multi-line comments by placing an apostrophe at the beginning of each line. This is useful for longer explanations or for commenting out blocks of code during debugging.
    • Example:
      ' This section of code calculates the total amount after applying
      ' discounts, taxes, and shipping fees. It ensures that all discounts
      ' are applied before calculating taxes.
      totalAmount = price - discount + tax + shipping
      

2.3. Block Commenting

  • Use block comments when you want to comment out multiple lines of code temporarily. This is helpful when you need to test a portion of code by disabling it.
    • Example:
      'Block comment to disable code
      ' totalAmount = price * quantity
      ' discountAmount = totalAmount * 0.1
      

3. Best Practices for Commenting

3.1. Explain "Why," Not Just "What"

  • Instead of commenting on what the code is doing (which is often clear from the code itself), focus on explaining why certain decisions or approaches were used.
    • Example:
      ' Calculate price with tax; tax is fixed at 10% for simplicity
      priceWithTax = price * 1.1
      

3.2. Keep Comments Concise and Relevant

  • Avoid writing excessive comments that could clutter your code. Comments should be brief and to the point, providing only the necessary context.
    • Example:
      ' Set the discount rate to 5%
      discountRate = 0.05
      

3.3. Use Comments for Code Structure

  • Use comments to section off major blocks of code to make your program more organized and navigable. This is especially helpful in larger projects.
    • Example:
      '===========================
      ' Data Input Section
      '===========================
      inputData = GetData()
      

3.4. Update Comments Regularly

  • As your code evolves, keep comments updated. Outdated comments can be more confusing than helpful and can mislead others (or yourself) when revisiting the code later.

4. Documenting Code: More than Just Comments

4.1. Use Header Comments

  • At the beginning of modules, functions, or procedures, provide header comments that briefly describe the purpose, parameters, and expected results of the code.
    • Example:
      '===========================================================
      ' Function: CalculateTotalAmount
      ' Purpose: Calculates the total order amount including tax
      ' Parameters: price (Double) - The base price of the item
      '             quantity (Integer) - The number of items ordered
      ' Returns: Double - The total order amount
      '===========================================================
      Function CalculateTotalAmount(price As Double, quantity As Integer) As Double
          CalculateTotalAmount = price * quantity * 1.1 ' Price including tax
      End Function
      

4.2. Documenting Complex Logic

  • For sections of code that implement complex algorithms or calculations, consider documenting the logic in detail. This helps future developers understand the reasoning behind the code.
    • Example:
      ' Loop through each item in the cart and apply the discount
      ' The discount is applied progressively based on the quantity
      For Each item In cartItems
          If item.Quantity > 10 Then
              item.Discount = 0.2 ' 20% discount for large quantities
          Else
              item.Discount = 0.1 ' 10% discount for smaller quantities
          End If
      Next item
      

4.3. Use Consistent Documentation Format

  • Establish a consistent format for documentation across your codebase. This could include certain tags like Parameters, Returns, Example, and Notes for clarity.
    • Example:
      '===========================================================
      ' Function: GetOrderDetails
      ' Purpose: Fetches the order details from the database
      ' Parameters: orderID (Integer) - The unique ID of the order
      ' Returns: Recordset - A recordset containing the order details
      ' Example:
      '    Set orderDetails = GetOrderDetails(1234)
      ' Notes:
      '    Ensure the orderID is valid before calling this function
      '===========================================================
      

5. Documenting External Dependencies

5.1. Mention Libraries and References

  • If your VBA code relies on specific libraries, references, or external components (e.g., ADO, DAO, Excel), document these dependencies clearly to ensure smooth setup and debugging.
    • Example:
      ' This module uses the ADO library to connect to external databases
      ' Ensure the Microsoft ActiveX Data Objects library is referenced
      

5.2. Use Version Control Comments

  • If applicable, add version control comments that indicate the version or revision of the code, along with a brief description of what changes were made.
    • Example:
      ' Version 1.2 - Updated to include error handling for network issues
      

6. Tools for Commenting and Documenting Code

6.1. Use VBA's Built-In Commenting Features

  • The VBA editor includes features like folding comments, which allows you to easily collapse or expand commented sections for better readability.

6.2. Consider Using External Documentation Tools

  • For larger projects, you might consider using external documentation tools (such as Doc-O-Matic or Sandcastle) that can automatically generate detailed documentation from comments in your code.

7. Conclusion

Commenting and documenting code in VBA is not just about adding notes or explanations—it’s about creating a helpful context that improves the readability, maintainability, and collaboration potential of your project. By following best practices, you can make your code more understandable for others and yourself in the future. Always aim for clarity, conciseness, and relevance when commenting, and keep your documentation up-to-date to ensure that it serves as an effective guide for anyone working with the code.

Commenting is not enabled on this course.