Using Named Arguments

Many built-in functions, statements, and methods take more than one argument. For example, the Open method, which opens a workbook, takes 12 arguments. If you want to write code that opens the workbook Book2.xls, which has the protection password "drowssap", you could write the following code.


Workbooks.Open "BOOK2.XLS", , , , "drowssap"

However, this code is difficult to write correctly without introducing bugs, because you have to count the number of commas to insert between the arguments. The code is also very difficult to read, and it gives no clues about what the arguments represent. The following example shows a better way to write this code.


Workbooks.Open fileName:="BOOK2.XLS", password:="drowssap"

Because every argument has a name, you can use the name and the := operator to assign a value to an argument. When you use named arguments, you don't have to remember the order of the arguments. For example, the preceding code could have been written with the order of the arguments reversed, as in the following example.


Workbooks.Open password:="drowssap", fileName:="BOOK2.XLS"

You can use named arguments with the procedures you create, too. Visual Basic automatically associates argument names with their corresponding procedures. For example, the FormatList procedure in the preceding section takes two required arguments and two optional arguments, as shown in the following declaration line.


Sub FormatList(startRow As Integer, startCol As Integer, _
        Optional redText, Optional sortList)

The following DoList procedure calls the FormatList procedure using named arguments.


Sub DoList()
    FormatList redText:=True, startCol:=2, startRow:=2
End Sub

The arguments are given out of order, and one of the optional arguments was omitted. Using named arguments is especially useful if your procedures have several optional arguments you don't always need to specify.

Note

You cannot use named arguments to avoid entering required arguments.