BaldyWeb

Your first function

Okay, you've got your feet wet with some VBA code behind forms and such.  Now you have some process that will need to be run from different places.  You were thinking maybe of copying your working code to each of those places, but hey, why have the same code all over the place?

Generally speaking you can create a Sub or a Function.  Both can accept arguments (values given to it when you call it), but only a function can return a value.  Since it's more flexible, let's create a function.  A function that will only be needed within a given form or report can be in that object's module, but more often you will want it in a standard module so it can be called from anywhere in the application.  If you put it in a standard module, make sure you don't name the module the same as the function, a common mistake.

The main components of the statement line are of course the name of the function, any input arguments, and the return value if desired.   While you can leave out the data types, it is always a good idea to specify them.  A function statement looks something like this:

Public Function YourFunctionName(strVariable As String, lngVariable As Long) As String
  'Your code here
End Function

You would call your function like this to have it execute a task:

YourFunctionName "test", 23

If you were getting a value returned from the function for testing, it might look like this:

If YourFunctionName("test", 23) = False Then

Home