Function Return Values VB Help

A new feature introduced with Visual Basic 6 is that function return values aren’t limited to simple data types like Integers or Strings. Functions may now return ‘custom data types and even arrays. This is a new feature of the language, so we’ll explore it in depth and look at a few examples too. The ability of functions to return all types of data makes them very flexible and can simplify coding.

Functions Returning Custom Data Types

The custom data type returned by a function must be declared in a Module. Suppose you need a function that returns a customer’s savings and checking balance. The custom data type must be defined as follows:

Type CustBalance
BalSavings As Currency
BalChecking As Currency
End Type

Then, we can define a function that returns a CustBalance data type as:

Function GetCustBalance(custID) As CustBalance {statements}
End Function

The GetCustBalance() function must be defined in the same Module as the declaration of the custom data type it returns. If you place the function’s definition in a Form’s code, then you’ll get a syntax error during the compilation of the project.

When you call this function, you must assign its result to a variable of the same type. First declare the variable, then use it as shown here:

Private Balance As CustBalance
Balance = GetCustBalance(custID)

Here, custID is a customer’s ID (a number or-string, depending on the application). Of course, you must assign the proper values to the CustBaIance variable’s fields.

Here’s the simplest example of a function that returns a custom data type. This example outlines the steps you must repeat every time you want to create functions that return custom data types:

1. Add a new Module to the project (or open the application Module, if it exists). Insert the declarations of the custom data type. For example:

Type CustBalance
BalSavings As Currency
BalCheckin9 As Currency
End Type

2. Then implement the function. you must declare a variable of the type returned by the function and assign the proper values to its fields. The following function assigns random values to the fields BalChecking and BalSavings. Then, assign the variable to the function  name, as shown next:

3. Switch to the Code window of the Form from which you want to call the function and declare a variable of the same type. Assign the function’s ” return value to this variable and use it in your code. The example that follows prints the savings and checking balances on the Immediate window


For this example, I created a project with a Form and a Module. The Form contains a single Command button whose Click event handler is shown here. Create this project from scratch, perhaps using your own custom data type, to explore its structure and experiment with functions that return custom data types.

In the following section I’ll describe a more complicated (and practical) example of a custom data type function.

VB6 at Work: The Types Project

The Types project,.which you’ll find in this chapter’s folder on the CD, demonstrates a function.that returns” a custom data type. The Types project consists of Form that displays, record fields and is shown in Figure 3.5. Every time you click the Show Next button the fields of the next record are displayed. When all records are exhausted, the program wraps back to the first record.



The project consists of a Form and a Module. The following custom data type appears in the Module:

The array Customers holds the data for 10 customers and the cust variable is used as a temporary variable for storing the current customer’s data.

The Click event handler ~f the Show Next button keeps track of the current record and calls the GetCustomer() function with an index value (which is the order of the current customer) and displays its fields in the Label controls on the Form.

The GetCustomer() function returns a variable of Customer type (the variable a Customer). The code behind the Show Next button follows.

The CountCustomers() function returns the number of records stored in the Customers() array. The definitions of the CountCustomers() and GetCustomer() functions appear in the project’s Module and they are:

The array Customers is populated when the program starts with a call to the InitData() subroutine (also in the project’s Module). The program assigns data to the Customers array, one element at a time, with statements like the following:

The code assigns values to the fields of the cust variable and then assigns the entire variable to an element of the Customers array. The data could originate in a file or even a database, This wouldn’t affect the operation of the application, which expects the GetCustomer() function to return a record of Customer type. If you decide to store the records in a random access file, or a Collection, the Form’s code need not change, only the implementation of the GetCustomer() function in the project’s Module.

Functions Returning Arrays

In addition to returning custom data types, Visual Basic 6 functions can also return arrays. This is an interesting possibility that allows you to write functions that return more than a single value. With previous versions of Visual Basic, functions could return multiple values by setting the values of their arguments. Let’s say you need a function that calculates the basic statistics of a data set. The basic
statistics are the-mean value (average), the standard deviation, and the minimum and maximum values in the data set. One way to declare a function that calculates all the statistics is the following:

Function ArrayStats(DataArray()· As Double, Average As Double_ StdDeviation As Double, MinValue As Double, MaxValue As Double)

The function’s type doesn’t really matter, since this function doesn’t return a value. The DataArray array contains the data values. This argument is passed by the calling procedure and it’s not modified by the function. The remaining arguments must be passed by reference, so that the ArrayStats() function can set their values. The calling procedure need not set their values. These arguments will be
set by the function and will be read by the calling procedure upon the function’s return.

With Visual Basic 6 you can declare a function that returns an array of values. The first element of the.array could contain the average value, the second element could contain the standard deviation, and so on. The declaration of the new function should be:

Function ArrayStats(DataArray() As Double) As Double()

This function accepts an array with the data values and returns an array of doubles. This notation is more compact and helps you write easier-to-read code.

To implement a function that returns an array, you must do the following:

1. Specify a type for the function’s return value and add a pair of parentheses after the type’s name. Don’t specify the dimensions of the array to be returned.

2. In the function’s code, declare an array of the same type and specify its dimensions. If the function should return four values, use a declaration like the following one:
Dim Results(3) As Double
The Results array will be used to store the results and must be of the same type as the function. Its name can be anything.

3. Before exiting the function, assign the array to the function name:
ArrayStats = Results()

4. In the calling procedure, you must declare an array of the same type without dimensions:
Dim Stats() As Double

5. Finally, you must call the function and assign its return value to this array:
Stats() = ArrayStats(DataSet())

Here, DataSet is an array with the values whose basic statistics will be calculated by the ArrayStats() function. Your code can then retrieve each element of the array Stats() with an index value as usual.

VB6 at Work: The Stats Project

The next project demonstrates how to design and call functions that return arrays. It’s the Stats project, which you can find in the Stats folder’ under this chapter’s folder on the CD. When you run it, the Stats application creates a data set of random values and’ then calls the ArrayStats() function to calculate the data set’s basic statistics. The results are returned in an array and the main program displays them in Label controls, as shown in Figure 3.6. Every time you click the button Show Statistics, a new data set is generated and its statistics are displayed.



The function’s return type is Doublet), meaning the function will return an array of doubles. That’s what the empty pair of parentheses signifies. This array is declared in the function’s body with the statement:

Dim Res(4) As Double

This function returns four values, but we use I-based arrays (that why its maximum index is 4 and not 3). The function performs its calculations and then assigns the values of the basic statistics to the elements of the array Res.The first element holds the average,the second element holds the standard deviation, and the other -two elements hold the minimum and maximum data values. The Res array is finally returned to the calling procedure by the statement that assigns the array’ to the function name, just as you’d assign a variable to the name of the function that returns a single result.

The code behind the Show Statistics button, which calls the ArrayStats() function, is shown next:

The code generates 100 random values and displays them on a ListBox control. Then, it calls the ArrayStats() function passing the data values to it through the SData array. The function’s return values are stored in the Stats array, which is declared as Double but without dimensions. Then, the code displays the basic statistics in the Label controls that form the lblSTATS array of controls with index values from 0 to 3.

Errors as Function Return Values

What happens when an error occurs during the course of the execution of a function? Many programmers will display an error message from within the function’s :ode and exit. An alternative is to convert the return value of the function to an error object and exit the function normally. The calling program can examine the function’s return value and determine whether an error occurred. If the function’s return value is not an error, then it’s the expected result.

Let’s say you’ve implemented the function Calculate() to evaluate a math expression. In evaluating a math expression, all types of errors can occur. For example, the code may attempt to evaluate the square root of a negative number, or the exponential of a large number that results in an overflow. If the Calculate() function is called from many places m the application, it won’t be easy to handle errors from within the function itself Displaying a message describing a math error isn’t going to help the user. However, it you let the main procedure handle the error, you may be able to display a more meaningful result like “The initial conditions you specified resulted in a math error” and give the user a chance to revise the data. This option isn’t available from within the Calculate() function.

If everything goes well, the Calculate() function will return its result as usual. If an error occurs during the calculations, the function should return an error object. To convert a value to an error object, use he CVError() function:

If Error Then
Calculate = CVError()
End If

The procedure that calls the Calculate() function can examine the function’s return value to determine whether an error occurred:

The Result variable must be of variant type, so that it can store both the actual result.Ian Integer, Double, or other data type, including custom data types) and he error object returned by the function.

Posted on November 5, 2015 in Visual Basic: The Language

Share the Story

Back to Top
Share This