VBA 类模块 - 设置默认值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24815394/
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
VBA Class Module - Setting default values
提问by Bj?rn H. Sandvik
I've only just started wrapping my head around building classes in Class Modules for VBA. It has been fairly smooth sailing so far, but I ran into a small challenge which is very easily solved if I were making a conventional function in a Module: How can I set an optional boolean default value to True?
我才刚刚开始在 VBA 的类模块中构建类。到目前为止,它的航行相当顺利,但我遇到了一个小挑战,如果我在模块中创建一个传统函数,这个问题很容易解决:如何将可选的布尔默认值设置为 True?
In a function or sub, I would simply solve this in the property list by implicit declaration:
在函数或子函数中,我只需通过隐式声明在属性列表中解决这个问题:
Function SomeFunction(Optional bValue = True) as Variant
...
End Function
In a Class Module using Let and Get properties, I haven't quite found my way around it yet since VBA defaultedly declares a Boolean variable as false. So I have, e.g.:
在使用 Let 和 Get 属性的类模块中,我还没有完全找到解决方法,因为 VBA 默认将布尔变量声明为 false。所以我有,例如:
Private bValue as Boolean
Public Property Let TrueOrFalse(myBoolProperty As Boolean)
bValue = myBoolProperty
End Property
Private Property Get TrueOrFalse() As Boolean
TrueOrFalse = bValue
End Property
Function SomeFunction() As Boolean
SomeFunction = TrueOrFalse
End Function
Bear in mind, I'm still learning, so even this simple code might be unsexy to the trained eye, but the question remains: How can I default bValue to True if I only want to use it as an Optional property?
请记住,我仍在学习,所以即使是这个简单的代码对训练有素的眼睛来说也可能不合时宜,但问题仍然存在:如果我只想将 bValue 用作 Optional 属性,我如何将它默认为 True?
Hopefully that made some sense..
希望这是有道理的..
Thank you for reading!
感谢您的阅读!
回答by David Zemens
The Class_Initialize method will allow you to set default values.
Class_Initialize 方法将允许您设置默认值。
I set up my properties like:
我设置了我的属性,如:
Option Explicit
Dim pTrueOrFalse as Boolean
'## This method will be invoked whenever you create a class object using the NEW keyword/etc.
Private Sub Class_Initialize()
pTrueOrFalse = True
End Sub
'## Property "Get" method, which returns the value when called
Public Property Get TrueOrFalse() As Boolean
TrueOrFalse = pTrueOrFalse
End Property
'## Property "Let" method, which assigns the value when called
Public Property Let TrueOrFalse(lTrueOrFalse as Boolean)
pTrueOrFalse = lTrueOrFalse
End Property
When using these in your regular code, you can do something like:
在常规代码中使用这些时,您可以执行以下操作:
Dim myClassObject as New [class object name] 'this will invoke the Initialize procedure
MsgBox myClassObject.TrueOrFalse 'this will call upon the "Get" method
myClassObject.TrueOrFalse = False 'This will call upon the "Let" method
MsgBox myClassObject.TrueOrFalse