问题描述
在旧的宏中,我像
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?
推荐答案
您的当前情况如下:
Dim a As Long, b As Long, c As Long
Sub proc1()
End Sub
Sub proc2()
End Sub
第二次运行proc1()时,避免a,b和c仍然有值的第一种方法是在proc1()上重新初始化它们:
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
另一种方法,您可以将变量作为参数传递,并仅在proc1()上声明它们:
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
或者,最后,您可能会考虑使用一个集合而不是使用N个变量.示例:
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
我对N个变量(公共声明或私有声明+重新初始化)所说的内容也适用于集合,但仅一次而不是N次(这就是为什么我会简化)的原因.
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).
这篇关于在一行中以零声明多个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!