I created a class module in Access VBA for stock price information. For reasons I can't figure out, when I try to assign currency values in my tests, my instance always are 0. Other data types (strings and dates) seem to work fine. Can anyone spot what I'm doing wrong?
Here is the relevant section from my class module:
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
When I run this test:
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
My results are always the same:
AMD 1/10/2019 Advanced Micro Devices Information_Technology 0 0
What trick am I missing to assign values to currency data types?
Your problem is in the Get()
method of your property.
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
For the property Price
, for example, dollar
is just a local variable you used in the Set()
method. However, once you go out of the method set, that variable is trashed by the garbage collector and becomes 0
(default value).
Hence, when you try to get it back, you get the current value of it (which is 0
).
I guess you're doing it right for the other properties, but since you didn't share the code I can't confirm.
Someone suggested you in the comment to put Option Explicit
on top of your module, it would help to avoid this kind of mistake (in your case, the variable dollar
wouldn't be defined in the context of Public Property Get Price() As Currency
and so you would get a compile error).