...Because someone's gotta tell the story...


To return to the main Blog List, click Full Blog Listing.


Visual Basic

Passing Functions (and not Global Variables) in Visual Basic

Tuesday, February 26, 2008 in Technical Articles (Views: 3015)
At times, I take requests for blogs, just general techie things that come to mind or my attention...

One developer was using a lot of public or global variables in his code, and not passing functions to process data. In short, here is how a function is passed without using a global variable.

Here is the code, explanation to follow...

Function DivideByTwo(Number1 As Integer)

'In this example, we are going to take the variable, Number1 and divide

'it by 2, returning the results back to the function.

DivideByTwo = Number1 / 2

End Function

...and of course we need a routine to call the function...

Private Sub Form_Load()

'You can either define a variable here and call the funtion into the variable

'or just call it directly, as in the msgbox function.

'Option 1: Defining a Variable and Calling the MsgBox

Dim intTemp As Integer

intTemp = DivideByTwo(18)

msgBox intTemp

'Option 2: Call the MsgBox and Function directly.

MsgBox DivideByTwo(18)

End Sub

So, looking back, we load the form. We can either load inTemp with the variable, or call the MsgBox directly with it, without declaring a variable.

The function itself, called DivideByTwo, consists of a single line that divides the numbers, and returns the result to the function (DivideByTwo).

This is how a function is passed without global variables in Visual Basic.


Related Blogs You May Be Interested In:

To leave a comment, please log in and/or register.