在VBA模块中,我有以下常量声明:
Private Const const_abc = 3000
Private Const const_def = 900
Private Const const_etc = 42
' and so on and so forth
现在,我必须使用一次函数调用来初始化这些值,理想情况是这样的
Private Const const_abc = someFunc(18)
Private Const const_def = someFunc( 7)
Private Const const_etc = someFunc( 5)
' and so on and so forth
当然,这在VBA中不起作用。那么,是否有一个关于如何处理这种要求的共同模式?
我可能会这样做
Private const_abc As Double
Private const_def As Double
Private const_etc As Double
sub initConsts()
const_abc = someFunc(18)
const_def = someFunc( 7)
const_etc = someFunc( 5)
end sub
但是我必须确保调用initConsts
,我宁愿不这样做。
修改根据 S O 的问题,我使用的是MS-Access。
答案 0 :(得分:3)
创建一个读取单元格的类,并为该值提供Get
- 唯一的接口。
这是一个名为ItsMyValueClass
选项明确
Private pMyVal As Integer
Public Property Get MyValue() As Integer
MyValue = pMyVal
End Property
Private Sub class_initialize()
'pMyVal = Sheet.Range("somewhere)
pMyVal = 17
End Sub
以下是模块中的代码:
Option Explicit
Sub IsItReadOnly()
Dim valu As ItsMyValueClass
Dim x As Integer
Set valu = New ItsMyValueClass
x = valu.MyValue
'valu.MyValue = 23 'compile error "Can't assign to read-only property"
End Sub
答案 1 :(得分:1)
Public Function White() as Long
White = RGB(255,255,255)
End function
Private Sub TestIt()
Debug.Print "White is " & White
White = 123 ' <-- compile error
End Sub
答案 2 :(得分:0)
在与模块和类一起使用的内联中,用于纯常数类访问:
Public Property Get myConst() As Integer: myConst = 3: End Property
您将这样使用它:
Sub test()
Debug.Print "myConst: " & myConst 'would print: "myConst: 3"
End Sub
和如果必须使用自定义值初始化一次,则可以使用静态属性和一个或多个私有变量来完成它:
Private ci As Boolean 'constants initialized
Private myConst1_ As Integer
Private myConst2_ As Integer
Static Property Get myConst1() As Integer
If Not ci Then init
myConst1 = myConst1_
End Property
Static Property Get myConst2() As Integer
If Not ci Then init
myConst2 = myConst2_
End Property
Private Sub init()
'these can come from anywhere:
myConst1_ = 3
myConst2_ = 5
ci = True
End Sub
init
函数(并且可以选择删除ci
变量和所有相关行,如果可以确保不更早访问属性)< / li>