Bjø*_*vik 2 excel vba excel-vba
我刚刚开始围绕VBA类模块中的构建类开始.到目前为止,它已经相当顺利,但我遇到了一个很小的挑战,如果我在模块中创建一个传统的函数,这很容易解决:如何将可选的布尔默认值设置为True?
在函数或子函数中,我只需通过隐式声明在属性列表中解决此问题:
Function SomeFunction(Optional bValue = True) as Variant
...
End Function
Run Code Online (Sandbox Code Playgroud)
在使用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
Run Code Online (Sandbox Code Playgroud)
请记住,我还在学习,所以即使这个简单的代码对于受过训练的人来说也可能是不合适的,但问题仍然存在:如果我只想将它作为Optional属性使用它,我如何将bValue默认为True?
希望这有点道理..
谢谢你的阅读!
Class_Initialize方法将允许您设置默认值.
我设置了我的属性,如:
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
Run Code Online (Sandbox Code Playgroud)
在常规代码中使用这些代码时,您可以执行以下操作:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7617 次 |
| 最近记录: |