- 30 Jan 2024
- Print
- PDF
Subroutines and Functions
- Updated on 30 Jan 2024
- Print
- PDF
Basic Subroutine with Error Handling
In general, subroutines in PARCcalc Config will begin with the following:
Option Explicit
Sub SubRoutineName()
On Error GoTo errhandler
The subroutine should then end with the following:
Exit Sub
errhandler:
errorcallback(Err,Error)
Resume Next
End Sub
Any other code will typically be placed in between these two sections.
Sub.....End Sub.......Call
Sometimes it is helpful to put code into its own module. Here is an example of a subroutine called SaveSquarerootOfSum that takes the input and output tag names as arguments:
Sub SaveSquarerootOfSum(TagIn1 as Integer, TagIn2 as Integer, TagOut as Integer)
Tag(TagOut, sqr(GD(TagIn1) + GD(TagIn2)))
End Sub
In this case, “Call” (with parameters) executes the subroutine. The following is an example:
‘calculate the square root of the sum of Input tags 2 and 5. Put the result in Output tag 4
Call SaveSquarerootOfSum(2, 5, 4)
‘calculate the square root of the sum of Input tags 19 and 21. Put the result in Output tag 6
Call SaveSquarerootOfSum(19, 21, 6)
Function.....End Function
Sometimes it is helpful to put code its own module. Following is an example. The function name (SaveSquarerootOfSum) is a variable that contains the value that is returned.
Name the Function “SquarerootOfSum” and define the input tags. The Function must be given a type at the end of the declaration (“Single”). The Function name must be assigned a value inside the routine.
Function SquarerootOfSum(TagIn1 as Integer, TagIn2 as Integer, TagOut as Integer) as Single
SquarerootOfSum = sqr(GD(TagIn1) + GD(TagIn2))
End Function
This function can then be called in other portions of the code. The following is an example:
‘calculate the square root of the sum of Input tags 2 and 5. Put the result in Output tag 4
Tag(4, SaveSquarerootOfSum(2, 5))
‘calculate the square root of the sum of Input tags 19 and 21. Put the result in Output tag 6
Tag(6, SaveSquarerootOfSum(19, 21))