【发布时间】:2016-01-05 06:28:52
【问题描述】:
我正在编写一个使用全局变量的项目。全局变量在模块开头声明,所有代码都在同一个模块内。全局变量(应该)在每个子例程之间传递,并且由于工作表的性质,它们的值根据需要在不同的子例程或函数中声明。
我的问题是每次调用子程序时,我的全局变量都会重置为0,这显然违背了拥有全局变量的目的。
有什么明显的原因可能导致这种情况吗?我的代码比较大(1200+ 行),在这里发帖不实用。
电子表格具有已删除和重绘的形状。这是否会重新编译工作表并导致所有全局变量重置?
谢谢
丹
编辑:变量声明
Public Type Blockwall
Asd As Single 'max area of reinforcement allowed
Ast As Single 'Area of reinforcement in design tension zone
Bar As Integer 'bar size
Capacity As Single 'Calculated capacity of wall usign Ast
cover As Single 'cover to reinforcement
d As Single 'Depth to centre of tension steel
Depth As Single 'Thickness of wall/footing
DesignMoment As Single 'Design Moment in base of wall
DL As Load 'Dead Load force
LL As Load 'Live Load Force
fc As Single 'Compressive strength of concrete/grout
fm As Single 'compressive strength of masonry
fsy As Single 'Design stress of steel
Height As Single 'Total height of wall/Length of Footing (sorry it is confusing)
Height190 As Single 'Height of 190 blockwork
Height290 As Single 'Height of 290 blockwork
Moment25 As Single 'moment 25% from the top
Moment50 As Single 'Moment 50% from the top
Moment75 As Single 'Moment 75% from the top
Phi As Single 'Capacity reduction factor
Spacing As Single 'Bar Spacing
X As Single 'Distance of resultant vertical force (Rotation Check)
End Type
Dim Wall As Blockwall
Dim Footing As Blockwall
和子程序的 sn-p,其中变量 Footing.Depth 被赋予了一个值(请注意,这只是一个为其赋值的位置):
Public Sub DrawWall(fLength As Single, fHeight As Single, kLength As Single, kHeight As Single, _
wHeight As Single, distToKey As Single, distToWall As Single, fBeta As Single, fPhi As Single, _
fDensity As Single, nBeta As Single, nPhi As Single, nDensity As Single, LL As Single, Height290 As Single)
'***---ASSIGN VALUES TO GLOBAL VARIABLES---***
Footing.Depth = fHeight
Footing.Height = fLength
子 DrawWall 被其他子调用以绘制所需的形状。调用 DrawWall 时似乎不会重置值,仅当我单击调用子例程的按钮时(或者我从代码编辑窗口启动子例程。)
【问题讨论】:
-
你的代码确实很大,但是你有sn-ps可以显示吗?大约 10 行或 12 行。还有你的全局变量。
-
您在一个使用全局变量的 VBA 模块中有 1200 行,并且存在错误。那里没有惊喜。您是否考虑过在类中重写或不使用全局变量?这似乎不是一个有用的评论,但如果你不尽快重写,你只会遇到越来越多的问题。您的全局变量被重置,因为它们在代码中的某处被显式重置。首先..你一开始有
Option Explicit吗?这将是一个好的开始。 -
我建议你研究一个class,这是一种在一段代码中定义逻辑和数据的方法,可以根据需要多次“实例化”。
-
当创建这些的例程(或调用者)完成时,您的项目将重置并且您的变量将丢失状态。
-
所有变量都会被状态丢失重置。您需要一个例程来重新加载它们。尽可能避免公共变量的众多原因之一。