Functions


Home           Programming       Favorites      

Using Functions is usually underused in all programming languages.  If they are used at all they are usually used to simply return a value, such as using Fahrenheit in the argument of the calling procedure and receiving the Centigrade temperature in return.

Another good technique is to break down a complex program into many small steps.  Put the steps in functions with a boolean return value and then have the main program call each step. 

An example of two lines in your main program would be:

 'if Step1 returns false, then go to errHandler1
If Not Step1("Financial Data", 100, 4) _
Then GoTo errHandler2

'if Step2 returns false, then go to errHandler1
If Not Step2("SomeOtherStuff", 5, 2) _
Then GoTo errHandler3

The first line simply says that if  function Step1 is false then the method in Step1 has failed and go to errHandler2.  If Step1 is true then the method in Step1 has succeeded and continue on to Step 2.

Below is the code for 1 procedure and 2 boolean functions.

Sub ComplexProgram()

   'on error in ComplexProgram, go to errHandler1
   On Error GoTo errHandler1

   'if Step1 returns false, then go to errHandler1
   If Not Step1("Financial Data", 100, 4) _
   Then GoTo errHandler2

   'if Step2 returns false, then go to errHandler1
   If Not Step2("SomeOtherStuff", 5, 2) _
   Then GoTo errHandler3

   Exit Sub
errHandler1:
   'Notify user of failure.
   'and possible suggestions.
   MsgBox "ComplexProgram has failed internally", _
   vbCritical, "Program Failure"

errHandler2:
   'Notify user of failure.
   'and possible suggestions.
   MsgBox "Step1 of ComplexProgram has failed", _
   vbCritical, "Program Failure"

errHandler3:
   'Notify user of failure.
   'and possible suggestions.
   MsgBox "Step2 of ComplexProgram has failed", _
   vbCritical, "Program Failure"

End Sub			

The Step1 function:

c				

The Step2 function.

   Function Step2( _
   ByVal intFinancialData As String, _
   ByVal intNumberofRows As Integer, _
   ByVal intNumberofColumns As Integer) _
   As Boolean

   On Error GoTo errHandler1

   'Set initial value to False until it finishes.
   Step2 = False

   'Much of your code (especially methods)
   'goes in this area. For example,
   'this code could be to call your
   'method to add a table in Word
   'with 5 rows and 2 columns.

   'If it completes all the code above
   'without error then
   Step2 = True

   Exit Function
errHandler1:
   'Notify user of failure.

   'if err.number = 1 then
   'add additional possible solutions
   'for error 1 to the msgbox below.
   MsgBox "Step2 has failed for error2 reason", _
   vbCritical, "Program Failure"

   'if err.number = 2 then
   'add additional possible solutions
   'for error 2 to the msgbox below.
   MsgBox "Step2 has failed for error2 reason", _
   vbCritical, "Program Failure"

End Function