This section covers coding standards, including code comments, line continuation, and code indentation.
Code Comments
Comments improve code readability and are ignored during compilation.
Excel VBA: Use a single quote (') for single-line comments (inline or full-line). Example (sample path: Samples\ch01\Excel VBA\Comments.xlsm):
Function MySum(sngX As Single, sngY As Single) As Single
' Calculate the sum of two real numbers
MySum = sngX + sngY
End Function
Sub Test()
Debug.Print MySum(1, 2) ' Call the function to calculate the sum of 1 and 2
Debug.Print MySum(3, 5) ' Call the function to calculate the sum of 3 and 5
End Sub
Python: Use # for single-line comments and triple quotes (''') for multi-line comments. Example (sample path: Samples\ch01\Python\sam01-03.py):
# Define MySum for addition
def MySum(a, b):
return a + b
'''
Benefits of using functions: Encapsulate specific features into functions
for repeated calls when needed, improving programming efficiency and reducing code volume.
'''
print(MySum(1, 2)) # Repeatedly call MySum
print(MySum(3, 5))
print(MySum(8, 12))
Line Continuation
Break long lines using specific symbols.
Excel VBA: Use an underscore (_) preceded by a space. Example (sample path: Samples\ch01\Excel VBA\LineContinuation.xlsm):
' Insert a row above row 3 and copy the format of row 2
Rows(3).Insert Shift:=xlShiftDown, CopyOrigin:=xlFormatFromLeftOrAbove
' Break into two lines (note the space before the underscore)
Rows(3).Insert Shift:=xlShiftDown, CopyOrigin:= _
xlFormatFromLeftOrAbove
Python: Use a backslash (\). Example:
>>> sht.api.Rows(3).Insert(Shift=xw.constants.InsertShiftDirection.xlShiftDown, \
... CopyOrigin=xw.constants.InsertFormatOrigin.xlFormatFromLeftOrAbove)
Code Indentation
Indentation enhances code structure.
Excel VBA: No strict rules (commonly 2 or 4 spaces). Example (sample path: Samples\ch01\Excel VBA\Indentation.xlsm):
Sub Test()
Dim intSC As Integer
intSC = InputBox("Please enter a number:")
If intSC >= 90 Then
Debug.Print "Excellent"
ElseIf intSC >= 80 Then
Debug.Print "Good"
ElseIf intSC >= 70 Then
Debug.Print "Medium"
ElseIf intSC >= 60 Then
Debug.Print "Pass"
Else
Debug.Print "Fail"
End If
End Sub
Python: Use 4 spaces (no tabs). Example:
sc = int(input('Please enter a number:'))
if sc >= 90:
print('Excellent')
elif sc >= 80:
print('Good')
elif sc >= 70:
print('Medium')
elif sc >= 60:
print('Pass')
else:
print('Fail')