在新的VBA类模块中设置货币值

问题描述 投票:0回答:1

我在Access VBA中创建了一个用于股票价格信息的类模块。由于我无法弄清楚的原因,当我尝试在我的测试中分配货币值时,我的实例总是为0.其他数据类型(字符串和日期)似乎工作正常。谁能发现我做错了什么?

以下是我的课程模块的相关部分:

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

我的结果总是一样的:

和1/10/2019 Advanced Micro Devices Information Technology 0 0

我错过了为货币数据类型分配值的技巧?

vba class ms-access currency
1个回答
1
投票

您的问题在于您的财产的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

例如,对于属性Pricedollar只是您在Set()方法中使用的局部变量。但是,一旦您退出方法集,该变量将被垃圾收集器删除并变为0(默认值)。因此,当您尝试将其取回时,您将获得它的当前值(即0)。

我猜你正在为其他属性做正确的事,但由于你没有共享代码,我无法确认。

有人建议你在评论中将Option Explicit放在你的模块之上,这将有助于避免这种错误(在你的情况下,变量dollar不会在Public Property Get Price() As Currencyand的上下文中定义,所以你会得到一个编译错误) 。

© www.soinside.com 2019 - 2024. All rights reserved.