Comments
The single most important practice for writing clear, decipherable code is to add frequent comments.
Comments are lines in your code which act as notes to yourself or others, to explain what the code means or what it is doing. Comments are not executed during the running of the program, so have no impact on the result your macro. VBA considers any line that starts with an apostraphe (') to be a comment and the Excel VBA editor highlights these lines by colouring them in green, so you can see, at a glance, that they are comments and will not be executed.
See the example below, which shows comments used to clarify the details of a simple subroutine:
' Subroutine to search cells A1-A100 of the current active ' sheet, and find the cell containing the supplied string Sub Find_String(sFindText As String) Dim i As Integer ' Integer used in 'For' loop Dim iRowNumber As Integer ' Integer to store result in iRowNumber = 0 ' Loop through cells A1-A100 until 'sFindText' is found For i = 1 To 100 If Cells(i, 1).Value = sFindText Then ' A match has been found to the supplied string ' Store the current row number and exit the 'For' Loop iRowNumber = i Exit For End If Next i ' Pop up a message box to let the user know if the text ' string has been found, and if so, which row it appears on If iRowNumber = 0 Then MsgBox "String " & sFindText & " not found" Else MsgBox "String " & sFindText & " found in cell A" & iRowNumber End If End Sub |
Don't worry if you don't understand some of the code in the example above - this will be explained later in this tutorial. The example has been included simply to show how comments are used to to explain what each section of the code is for.
It is easy to get lazy about adding comments to your code, but it really is worth making the effort. - the minutes invested in ensuring your code is well commented could save you hours of frustration in the long run!
Comments
Post a Comment
jeetexceltips@gmail.com