For all intents and purposes, everything that happens in your code happens in procedures. Functions and subroutines ( subs ) are both types of procedures you can write. Both contain Visual Basic code ( statements ), and both can accept input ( arguments ).
The only real difference between functions and subroutines is that functions can directly return information to the calling procedure by assigning a value to the name of the function. This means you can use functions like variables , so functions should be declared as a certain data type, just like any other variable.
For example, the following code has a sub AddTask that calls a function strNewTask:
Function strNewTask(strName As String, intBefore As Integer) As String ActiveProject.Tasks.Add strName, intBefore If ActiveProject.Tasks(intBefore).Name = strName Then strNewTask = "Success!" Else strNewTask = "Failed to create task!" End If End Function Sub AddTask() MsgBox strNewTask("Write chapter", 3) End Sub
The Sub and End Sub, Function and End Function statements define the boundaries of the sub or function. As you can see, the statement declaring the function declares it as a particular data type, whereas the sub does not.
This code contains several other items worth noting:
The function has two arguments, strName and intBefore, which are declared just like any other variables, even though they are part of the function declaration.
To return a value from a function, you must first assign a value to the name of the function, as in the following line:
strNewTask = "Success!"
The MsgBox function takes several arguments, one of which is a String that contains the text to display in the dialog box. (It is itself a function because it can return information about which button the user clicked; by calling it without parentheses, we're discarding the Integer value that it would otherwise return.) Instead of being supplied as text in quotes (a string literal ) or even as a "traditional" variable, the argument is supplied as the return value of the function strNewTask.