在新 VBA Class 模块中设置货币值
Set currency values in new VBA Class module
我在 Access VBA 中创建了一个 class 模块来获取股票价格信息。由于我无法弄清楚的原因,当我尝试在测试中分配货币值时,我的实例始终为 0。其他数据类型(字符串和日期)似乎工作正常。谁能发现我做错了什么?
这是我的 class 模块中的相关部分:
Public Property Let Price(ByVal dollar As Currency)
pPrice = dollar
End Property
Public Property Get Price() As Currency
dollar = pPrice
End Property
Public Property Let Peak(ByVal amt As Currency)
pAmt = amt
End Property
Public Property Get Peak() As Currency
amt = pAmt
End Property
当我运行这个测试:
Sub TestStock()
Dim st As Stock
Set st = New Stock
st.Symbol = "AMD"
st.CreateDt = #1/10/2019#
st.Name = "Advanced Micro Devices"
st.Industry = Information_Technology
st.Price = 19
st.Peak = 24
Debug.Print st.Symbol, st.CreateDt, st.Name, st.IndustryText, st.Price, st.Peak
Set st = Nothing
End Sub
我的结果总是一样的:
AMD 1/10/2019 高级微设备 Information_Technology 0 0
我缺少什么技巧来为货币数据类型赋值?
您的问题出在 属性 的 Get()
方法中。
Public Property Get Price() As Currency
dollar = pPrice '<-- wrong, dollar means nothing in this context
Price = pPrice '<-- right, that's the property you want to Get
End Property
例如属性Price
,dollar
只是您在Set()
方法中使用的局部变量。但是,一旦您离开方法集,该变量就会被垃圾收集器丢弃并变为 0
(默认值)。
因此,当您尝试取回它时,您会得到它的当前值(即 0
)。
我猜你对其他属性的做法是正确的,但由于你没有共享代码,我无法确认。
有人在评论中建议你把 Option Explicit
放在模块的顶部,这将有助于避免这种错误(在你的情况下,变量 dollar
不会被定义在 Public Property Get Price() As Currency
的上下文中,所以你会得到一个编译错误。
我在 Access VBA 中创建了一个 class 模块来获取股票价格信息。由于我无法弄清楚的原因,当我尝试在测试中分配货币值时,我的实例始终为 0。其他数据类型(字符串和日期)似乎工作正常。谁能发现我做错了什么?
这是我的 class 模块中的相关部分:
Public Property Let Price(ByVal dollar As Currency)
pPrice = dollar
End Property
Public Property Get Price() As Currency
dollar = pPrice
End Property
Public Property Let Peak(ByVal amt As Currency)
pAmt = amt
End Property
Public Property Get Peak() As Currency
amt = pAmt
End Property
当我运行这个测试:
Sub TestStock()
Dim st As Stock
Set st = New Stock
st.Symbol = "AMD"
st.CreateDt = #1/10/2019#
st.Name = "Advanced Micro Devices"
st.Industry = Information_Technology
st.Price = 19
st.Peak = 24
Debug.Print st.Symbol, st.CreateDt, st.Name, st.IndustryText, st.Price, st.Peak
Set st = Nothing
End Sub
我的结果总是一样的:
AMD 1/10/2019 高级微设备 Information_Technology 0 0
我缺少什么技巧来为货币数据类型赋值?
您的问题出在 属性 的 Get()
方法中。
Public Property Get Price() As Currency
dollar = pPrice '<-- wrong, dollar means nothing in this context
Price = pPrice '<-- right, that's the property you want to Get
End Property
例如属性Price
,dollar
只是您在Set()
方法中使用的局部变量。但是,一旦您离开方法集,该变量就会被垃圾收集器丢弃并变为 0
(默认值)。
因此,当您尝试取回它时,您会得到它的当前值(即 0
)。
我猜你对其他属性的做法是正确的,但由于你没有共享代码,我无法确认。
有人在评论中建议你把 Option Explicit
放在模块的顶部,这将有助于避免这种错误(在你的情况下,变量 dollar
不会被定义在 Public Property Get Price() As Currency
的上下文中,所以你会得到一个编译错误。