Procedures

In VBA, macros are referred to as procedures. There are two types of procedures — sub procedures and function procedures. You will find out about function procedures in the next section. The macro recorder can only produce sub procedures. You can see the MonthNamesl sub procedure set up by the recorder in Figure 1-5.

Sub procedures start with the keyword Sub, followed by the name of the procedure and opening and closing parentheses. The end of a sub procedure is marked by the keywords End Sub. Although it is not mandatory, the code within the sub procedure is normally indented to make it stand out from the start and end of the procedure, so that the whole procedure is easier to read. Further indentation is normally used to distinguish sections of code such as If tests and looping structures. For example:

If ActiveCell.Value = 10 Then

ActiveCell.Font.Bold = True End If

Any lines starting with a single quote are comment lines, which are ignored by VBA. They are added to provide documentation, which is a very important component of good programming practice. You can also add comments to the right of lines of code. For example:

Range("B1").Select 'Select the B1 cell

At this stage, the code may not make perfect sense, but you should be able to make out roughly what is going on. If you look at the code in MonthNamesl, you will see that cells are being selected and then the month names are assigned to the active cell formula. You can edit some parts of the code, so if you had spelled a month name incorrectly, you could fix it; or you could identify and remove the line that sets the font to bold; or you can select and delete an entire macro.

Notice the differences between MonthNamesl and MonthNames2. MonthNamesl selects specific cells such as B1 and C1. MonthNames2 uses Offset to select a cell that is zero rows down and one column to the right from the active cell. Already, you are starting to get a feel for the VBA language.

0 0

Post a comment