Читать книгу Excel 2019 Power Programming with VBA - Michael Alexander, Dick Kusleika - Страница 139

Entering VBA code

Оглавление

VBA code, which resides in a VBA module, consists of instructions. The accepted practice is to use one instruction per line. This standard isn't a requirement, however; you can use a colon to separate multiple instructions on a single line. The following example combines four instructions on one line:

Sub OneLine() x= 1: y= 2: z= 3: MsgBox x + y + z End Sub

Most programmers agree that code is easier to read if you use one instruction per line.

Sub MultipleLines() x = 1 y = 2 z = 3 MsgBox x + y + z End Sub

Each line can be as long as you like; the VBA module window scrolls to the left when you reach the right side. However, reading very long lines of code while having to scroll is not a particularly pleasant. For lengthy lines, it's considered a best practice to use VBA's line continuation sequence: a space followed by an underscore (_). Here's an example:

Sub LongLine() SummedValue = _ Worksheets("Sheet1").Range("A1").Value + _ Worksheets("Sheet2").Range("A1").Value End Sub

When you record macros, Excel often uses the line continuation sequence to break a long statement into multiple lines.

After you enter an instruction, VBA performs the following actions to improve readability:

 It inserts spaces between operators. If you enter Ans=1+2 (without spaces), for example, VBA converts it to the following:

Ans = 1 + 2

 It adjusts the case of the letters for keywords, properties, and methods. If you enter the following text:

Result=activesheet.range("a1").value=12

VBA converts it to the following:

Result = ActiveSheet.Range("a1").Value = 12

Notice that text within quotation marks (in this case, "a1") isn't changed.

 Because VBA variable names aren't case-sensitive, the VBE, by default, adjusts the names of all variables with the same letters so that their case matches the case of letters that you most recently typed. For example, if you first specify a variable as myvalue (all lowercase) and then enter the variable as MyValue (mixed case), the VBA changes all other occurrences of the variable to MyValue. An exception occurs if you declare the variable with Dim or a similar statement; in this case, the variable name always appears as it was declared.

 VBA scans the instruction for syntax errors. If VBA finds an error, it changes the color of the line and might display a message describing the problem. In the Visual Basic Editor, choose the Tools ➪ Options command to display the Options dialog box, where you control the error color (use the Editor Format tab) and whether the error message is displayed (use the Auto Syntax Check option in the Editor tab).

Excel 2019 Power Programming with VBA

Подняться наверх