vba 在一行中用零声明多个变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28472739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Declare multiple variables with zero in one line
提问by K?τ?
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?
是否可以通过声明将所有变量设置为零,以便我不必手动设置每个(数百个)变量?
回答by Matteo NNZ
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():
第二次运行 proc1() 时避免 a、b 和 c 仍然有值的第一种方法是在 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():
另一种方法,您可以将变量作为参数传递并仅在 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:
或者,最后,您可能会考虑使用集合而不是 N 个变量。例子:
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).
我所说的 N 个变量(公共声明或私有声明 + 重新初始化)也适用于集合,但只适用一次而不是 N 次(这就是我认为它会简化的原因)。