What are subroutines and functions?

Typically, complex applications written in Statistica (or any other) Visual Basic are structured. In other words, most programs will not consist of a single routine, but of many separate routines that will call each other. Every macro program (events, etc. are discussed in What are application events and how can they be controlled from Statistica Visual Basic?) consists of a Main program inside a Sub Main ... End Sub block. Inside the main program you can call subroutines and functions to perform repetitive tasks, or just to keep the structure of your program transparent. Here is an example program that consists of several subroutines and functions; note that the main program performs no computations, and only contains calls to the subroutines.

' This program will compute the sum of the ' squared values from 1 to 10. The program ' illustrates how subroutines and functions ' are declared, and how different numeric ' and string data types are declared and ' passed to subroutines and functions. Sub Main

' Declare x as an array of double values; ' there are 10 elements in this array, which ' can be addressed as x(1), x(2), etc. (i.e., ' the lower bound of the array is element 1, ' the upper bound is 10). Dim x (1 To 10) As Double Dim SumValue As Double, ResText As String ' The following subroutine will fill the array ' with numbers from 1 to 10. ComputeArray x() ' A function is called to compute the sum of ' the squared values in array x; note how ' we do not pass explicitly the lower and ' upper bounds for array x, but use functions ' (LBound, UBound) to retrieve those values. SumValue=ComputeSumOfSqrs ( LBound (x), _ UBound(x), _ x) ' The following subroutine makes the results string ' ResText. MakeResultsText SumValue,x(),ResText MsgBox ResText

End Sub

' In this subroutine, a For...Next loop is ' used to fill array x with values between ' 1 and 10. Sub ComputeArray(x() As Double)

Dim i As Integer For i =1 To 10 x(i)=i Next i

End Sub

' This function computes the sum of the squared ' values in an array of double numbers. The ' function returns a double value.

Function ComputeSumOfSqrs (iFrom As Long, _ iTo As Long, _ x() As Double) As Double

Dim i As Integer ComputeSumOfSqrs=0 For i= iFrom To iTo ComputeSumOfSqrs=ComputeSumOfSqrs+x(i)^2 Next i

End Function

' The following subroutine makes the results text, to be ' displayed at the end of the Main program.

Sub MakeResultsText(SumValue As Double, _ x() As Double, _ ResText As String)

ResText="The sum of the square of values from " + _ Str(LBound(x)) & _ " to " & _ Str(UBound(x)) & _ " is " & _ Str(SumValue)

End Sub