Finance

Charts

Statistics

Macros

Search

Splitting Long Lines of Code In Excel VBA

Long lines of code can be made more readable and manageable by splitting them into multiple lines using the underscore character _ (underscore) at the end of a line.

The following example demonstrates this using the previously known procedure for copying a worksheet  — admittedly in a somewhat exaggerated way:

Sub CopySheet()
    ThisWorkbook.Activate
    Worksheets _
        ("Sheet1"). _
        Copy _
        After:=Worksheets("Sheet1")
    ActiveSheet.Name = "Sheet1Copy"
End Sub

Explanation:

  • A line ending with an underscore _ indicates that the statement continues on the following line. This allows a single statement to span two or more lines for improved clarity.
  • Common break points include spaces between keywords like Copy and After, or between function parameters. This helps maintain readability.
  • In the example, additional break points are used after the word Worksheets and before the dot . preceding Copy. While this is somewhat excessive stylistically, it illustrates how very long object references — common in VBA when dealing with objects — can be split across multiple lines.
  • It is important to avoid placing the line break inside a word or within the double quotation marks that define string literals.
0 0 votes
Évaluation de l'article
S’abonner
Notification pour
guest
0 Commentaires
Le plus ancien
Le plus récent Le plus populaire
Online comments
Show all comments
Facebook
Twitter
LinkedIn
WhatsApp
Email
Print
0
We’d love to hear your thoughts — please leave a commentx