VBA全局类变量 [英] VBA global class variable
问题描述
我的障碍是试图获得多个子元素来识别类变量。当我尝试在全局声明它,我得到一个编译错误:外部程序无效。然后,当我运行一个public函数或者sub来声明变量时,它们在另一个子集中保持未定义。我想要多个subs来识别变量,因为它们的值应该通过UserForm进行更改,然后在不同的子节点中使用。
My obstacle is trying to get multiple subs to recognize class variables. When I try to declare them globally, I get a compile error: "Invalid outside procedure". Then, when I run a public function or sub to declare the variables, they remain undefined in the other subs. I want multiple subs to recognize the variables because their values are supposed to be altered via UserForm, and then utilized in a different sub.
如果它可以以这种方式工作,伟大的,但我明白我的设计可能从根本上是有缺陷的。请指教!
If it could work in this manner, great, but I understand that my design could fundamentally be flawed. Please advise!
这是我的Class定义,作为名为cRSM的Class模块插入:
This is my Class definition, inserted as a Class module named "cRSM":
Option Explicit
Private pName As String
Private pDesiredGrowth As Double
'Name of RSM
Public Property Get Name() As String
Name = pName
End Property
Public Property Let Name(Value As String)
pName = Value
End Property
'Growth property
Public Property Get DesiredGrowth() As Double
DesiredGrowth = pDesiredGrowth
End Property
Public Property Let DesiredGrowth(Value As Double)
If Value > 0 And Value < 1 Then
pDesiredGrowth = Value
End If
End Property
这是无效的程序错误(我放在全球声明部分):
This is invalid procedure error (which I put in the Global Declarations section):
'Bedoya
Dim Bedoya As cRSM
Set Bedoya = New cRSM
Bedoya.Name = "Bedoya"
这是变量未定义的错误(在私有子范围内):
And this is the "variable not defined error" (within a private sub):
Private Sub Add_Click()
**Bedoya.DesiredGrowth** = Txt2.Value
谢谢你的时间
推荐答案
如果我理解好想要一个全局对象。
If I understood well You want a global object.
您可以将声明放在模块像
You can put the declaration in module like
public Bedoya As cRSM
然后你创建对象...你可以使用工作簿中的全局事件,如
then you have create the object ... you can use a global event inside the Workbook like
Private Sub Workbook_Open()
Set Bedoya = New cRSM
Bedoya.initialize("Bedoya") 'a method to initialize private variables
End Sub
现在可以使用全局对象。您必须重新启动excel文件或手动运行此方法。
Now you can use the global object. You have to restart the excel file or run this method manually.
使用全局变量不是很好的风格,但有时候更容易做:P
Is not good style to use global variables, but sometimes is the more easy to do :P
现在你想做的是使用单一的软件模式,但这是另一天hehehe
What you want to do nowadays is done using singleton Software Pattern, but this is for other day hehehe
这篇关于VBA全局类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!