Home » VB 6.0 Tutorial » VB 6 Static Function

VB 6 Static Function

In the previous article, you learned about functions that returned values. The variables that return the value are of two types – global and local. The local variable gets destroyed every time we call the function in our program.

The only solution to this problem is to make variable or function retain its previous value. This can be achieved using the static keyword in VB 6.

Example: Without static keyword

In this example program a function is called each time a button is clicked and display the count using a message box.

Private Sub Command1_Click()
Dim clkCount As Integer

clkCount = counter()
MsgBox ("Result =" + Str(clkCount))
End Sub

Static Function counter() As Integer
Dim count As Integer
count = count + 1
counter = count
End Function

Output – static function

Output – Static Function

In the example above, each time a user clicks the button, the result is 1. The variable count is reset to 0. To retain the value of count either declare the variable as static or declare the entire function as static. One that’s done the function will retain the value even though we recall the function several times and increment the counter successfully.