Named Arguments

Some VBA procedures can contain a large number of parameters. For example, one form of the Excel SaveAs function has the declaration:

SaveAs (Filename As string, FileFormat As VARIANT, Password As VARIANT, _ WriteResPassword As VARIANT, ReadOnlyRecommended As VARIANT, _ CreateBackup As VARIANT, AddToMru As VARIANT, TextCodepage As _ VARIANT, TextVisualLayout As VARIANT)

where all of the parameters are optional. Here is an example of a call to this procedure:

SaveAs "c:\temp\test.xls", , , , , True , , , True

Not very readable, is it?

The arguments shown in the previous call are said to be positional arguments because it is their position that tells VBA which parameters they are intended to replace. This is why we need to include space for missing arguments.

However, VBA can also use named arguments, in which case the previous call would be written as:

SaveAs FileName:="c:\temp\test.xls", CreateBackup:=True, AddToMru:=True

Note the special syntax for named arguments, in particular, the colon before the equal sign.

This function call is a great improvement over the positional argument version. In general, the advantages of named arguments over positional arguments are threefold:

• Named arguments can improve readability and clarity.

• Blank spaces (separated by commas) are required for missing optional arguments when using a positional declaration, but not when using named arguments.

• The order in which named arguments are listed is immaterial, which, of course, is not the case for positional arguments.

Named arguments can improve readability quite a bit and are highly recommended. However, they can require considerably more space, so for the short examples in this book, we usually will not use them.

0 0

Post a comment