3
votes

How should I initialize variable value during the declaration.

I am using VB6, I tried

public i as integer = 0

but i got error

Expected: End of statement, and "=" is highlighted

I want to set initial value to 0.

Edit from comments:

I want to create a login form without the help of the database..

Module: So i created a user_name(1 to 10)-- array and password(1 to 10) array

form1 I want to register upto 10 users each time the value of i increments //form// i=1 register_user(i)=uname register_pass(i)=upass i=i+1 //end// but each time I go to that form value is set again to 1 what should I do.

3

3 Answers

10
votes

In VBA and VB6 you can't initialize variables. You must use an executable statement.

However, each variable does have a default initialization value.

From the VB6 documentation:

When variables are initialized, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string (""), and a fixed-length string is filled with zeros. Variant variables are initialized to Empty. Each element of a user-defined type variable is initialized as if it were a separate variable.

So actually, in your case,

public i as integer = 0

doesn't work, but the next stement does work, and does just that:

public i as integer
0
votes

I think the issue is that you are attempting to instantiate a public variable at declaration...Dim i As Integer: i = 1 works, but is not public. You can either do this or declare the public variable then instantiate it in the first line of of the sub.

0
votes

Vacip answered it in terms of setting it to 0 like you asked, but to build on it... If you need a public variable to start as something other than the default value you would set it to that value the first time it is called in a sub.

If you have multiple subs that might call it for the first time and then it gets passed back and forth, you need to check to ensure that it hasn't already been set. you can do that with a public boolean.

If you turn on your locals and step through this you can see one way to do it.

Public iTesti As Integer 'defaults to 0
Public bTesti As Boolean 'defaults to FALSE

Public Sub testi()
If bTesti = False Then 'btesti is false and iteseti is 0
    iTesti = 1
    bTesti = True
End If
iTesti = 2
testi2
End Sub

Public Sub testi2()
If bTesti = False Then 'btesti is true and itesti is 2
    iTesti = 1
    bTesti = True
End If
iTesti = 3
End Sub