Declare multiple variables with zero in one line

2019-09-05 15:58发布

In an old macro I declare many variables in one line like

Dim Jan_Bnm, Feb_Bnm, Mar_Bnm, Apr_Bnm, Mai_Bnm, Jun_Bnm, Jul_Bnm, Aug_Bnm, Sep_Bnm, Okt_Bnm, Nov_Bnm, Dez_Bnm

With this variables I make some calculations like

Jan_Bnm = Jan_Bnm + 1 
'e.g. empty = empty + 1 -> 1

Now I have the problem if the macro runs twice the old value is still stored

Jan_Bnm = Jan_Bnm + 1 
'1 = 1 + 1 -> 2

So all my values are doubled.

Is it possible to set all variables by declaration to zero so that I don't have to set every (some hundreds) variable manualy?

1条回答
Rolldiameter
2楼-- · 2019-09-05 16:10

Your current situation is the following:

Dim a As Long, b As Long, c As Long
Sub proc1()

End Sub
Sub proc2()

End Sub

The first way to avoid a, b and c still have a value when running proc1() the second time is to re-initialize them on proc1():

Sub proc1()
     a = 0
     b = 0 
     c = 0
     'rest of the code
End Sub

Another way, you could pass the variables as parameters and declare them only on proc1():

 Sub proc1()
      Dim a As Long, b As Long, c As Long
      'rest of the code
      proc2 a,b,c
 End Sub
 Sub proc2(ByVal a As Long, ByVal b As Long, ByVal c As Long)

 End Sub

Or, finally, you might think about working with a collection rather than with N variables. Example:

Dim myVars As New Collection
myVars.Add a
myVars.Add b
myVars.Add c

So now you will be able to reinitialize the variables as follows:

For j = 1 To myVars.Count
    myVars(j) = 0
Next j

And what I said for the N variables (public declaration or private declaration + re-initialization) is applicable to the collection as well, but only once instead of N times (that's why I think it would simplify).

查看更多
登录 后发表回答