A comment is descriptive text embedded within your code and ignored by VBA. It's a good idea to use comments liberally to describe what you're doing because an instruction's purpose is not always obvious.

You can use a complete line for your comment, or you can insert a comment after an instruction on the same line. A comment is indicated by an apostrophe. VBA ignores any text that follows an apostrophe -except when the apostrophe is contained within quotation marks - up until the end of the line. For example, the following statement does not contain a comment, even though it has an apostrophe:

Msg = "Can't continue"

The following example shows a VBA procedure with three comments:

Sub Comments()

' This procedure does nothing of value x = 0 'x represents nothingness ' Display the result

MsgBox x End Sub

Although the apostrophe is the preferred comment indicator, you can also use the Rem keyword to mark a line as a comment. For example:

Rem -- The next statement prompts the user for a filename

The Rem keyword is essentially a holdover from old versions of BASIC and is included in VBA for the sake of compatibility. Unlike the apostrophe, Rem can be written only at the beginning of a line, not on the same line as another instruction.

Tip Using comments is definitely a good idea, but not all comments are equally beneficial. To be useful, comments should convey information that's not immediately obvious from reading the code. Otherwise, you're just chewing up valuable bytes.

Following are a few general tips on making the best use of comments:

■ Use comments to describe briefly the purpose of each procedure that you write.

■ Use comments to describe changes that you make to a procedure.

■ Use comments to indicate that you're using functions or constructs in an unusual or nonstandard manner.

■ Use comments to describe the purpose of variables so that you and other people can decipher otherwise cryptic names.

■ Use comments to describe workarounds that you develop to overcome Excel bugs or limitations.

■ Write comments while you code rather than after.

Tip In some cases, you might want to test a procedure without including a particular instruction or group of instructions. Instead of deleting the instruction, simply turn it into a comment by inserting an apostrophe at the beginning. VBA then ignores the instruction(s) when the routine is executed. To convert the comment back to an instruction, just delete the apostrophe.

The Visual Basic Editor (VBE) Edit toolbar contains two very useful buttons. Select a group of instructions and then click the Comment Block button to convert the instructions to comments. The Uncomment Block button converts a group of comments back to instructions. These buttons are very useful, so you might want to copy them to your Standard toolbar.



0 0


Post a comment