excel - 如何改进这个类模块定义

标签 excel vba oop

我正在尝试创建一个类模块,该模块接受用户输入的两个参数,然后进行计算以创建返回计算值的私有(private)属性

这是我到目前为止得到的:

'clsItem Class Module
Option Explicit

Private mQt As Integer
Private mPrice As Double
Private mTotal As Double

Public Property Let Quantity(Value As Integer)
    mQt = Value
End Property

Public Property Let Price(Value As Double)
    mPrice = Value
End Property

Private Function SetTotal(mQt As Integer, mVl As Double)
    mTotal = mQt * mPrice
End Function

Public Property Get Quantity() As Integer
    Quantity = mQt
End Property

Public Property Get Price() As Double
    Price = mPrice    
End Property

Public Property Get Total() As Double
    SetTotal mQt, mPrice 'This smells
    Total = mTotal   
End Property

我评论的部分这味道是我拼凑而成的,所以下面的代码给出了预期的行为:

'Object Module
Sub TestCls()
    Dim basicItem As clsItem

    Set basicItem = New clsItem
    With basicItem
        .Quantity = 100
        .Price = 12.5
    End With
    Debug.Print basicItem.Total
End Sub

我认为这是错误的,因为

  1. 我正在使用 get 属性来调用函数,但我无法找到一种方法将此调用放置在代码的其他位置。
  2. 如果我不在模块中的某个位置调用 clsItem.TotalmTotal 将永远不会更新。

我尝试使用Class_Initialize(),但由于.Quantity.Price,它给出了0尚未传递给类(class)。

那么我怎样才能做到这一点呢?

最佳答案

  1. 删除SetTotal
  2. 只需在 Get Total() 中计算总计

所以你最终会得到

'clsItem Class Module
Option Explicit

Private mQt As Integer
Private mPrice As Double

Public Property Let Quantity(Value As Integer)
    mQt = Value
End Property

Public Property Get Quantity() As Integer
    Quantity = mQt
End Property


Public Property Let Price(Value As Double)
    mPrice = Value
End Property

Public Property Get Price() As Double
    Price = mPrice    
End Property


Public Property Get Total() As Double
    Total = mQt * mPrice
End Property

关于excel - 如何改进这个类模块定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53725989/

相关文章:

excel - 从html中获取属性字符串值

excel - 如何从 VBA 更改列名

vba - Excel 2007 VBA问题设置轴标题

python - 使用属性装饰器时 Python 中的行为不一致

javascript - 如何在 Vue 中使用 v-for 获取每个项目的计数?

java - 这个类是另一个类的子类型吗?

python - 将直方图从 Python 导出到 Excel

javascript - excel可以根据网站的变量填写某些字段吗?

excel - 1004 未找到单元格 - 错误处理

excel - 显示警报 VBA