在类模块中使用带参数的子项

时间:2019-01-12 11:40:25

标签: vba class module arguments

我在常规模块中有一个Sub,主要在其中进行代码。在类模块中,我有一个子类,它要求不是类模块本身属性的参数。现在我无法启动代码。

我用最少的行数编写了一个示例代码,因此您可以看到我打算做什么。

首先是类模块“ clsCity”:

Option Explicit

Public area As Single

'Public l As Single 'Working, but not desired solution:
'Public h As Single 'Working, but not desired solution:

Sub calcArea(length As Single, height As Single)

area = length * height

End Sub

现在程序本身:

Sub Country()

Dim BikiniBottom As New clsCity  
Dim l As Single
Dim h As Single


Bikinibottom.calcArea(l,h) 'Error: "vba: Compile Error: expected: ="

'Working, but not desired solution:
'Bikinibottom.calcArea 'Where l and h are properties of clsCity

End Sub

如您所见,我计划使用变量“ l”和“ h”来计算Bikinibottom的面积,这不是clsCity的属性。当按Enter键时,出现错误“ vba:编译错误:预期:=”。我做错了什么?这是一个子项,而不是一个函数,不需要使用“ =”。

我知道使用注释的代码会起作用。但是,这只是一个简短的示例,请记住,在我的实际代码中,将“ l”和“ h”设置为clsCity的属性(它们是其他类模块的属性!)不是复杂的解决方案。

2 个答案:

答案 0 :(得分:0)

好吧,我设法做到了:

在课程模块中:

BikiniBottom.area = BikiniBottom.calcArea(l, h)

并在我的主要代码中:

if (appBought) {

   //SOME_WORK_1

} else {

   //SOME_WORK_2

}

所以基本上我的问题解决了。 仍然好奇如何在类模块中使用带参数的Subs。想法?

答案 1 :(得分:0)

我会写这个

Option Explicit

Sub Country()

    Dim BikiniBottom As New clsCity

    BikiniBottom.Length = 2
    BikiniBottom.Height = 3

    Debug.Print BikiniBottom.area

End Sub

然后对于该类,我将使用属性过程...

Option Explicit

Private m_Length As Single
Private m_Height As Single

Public Property Let Length(rhs As Single)
    m_Length = rhs
End Property
Public Property Get Length() As Single
    Length = m_Length
End Property

Public Property Let Height(rhs As Single)
    m_Height = rhs
End Property
Public Property Get Height() As Single
    Height = m_Height
End Property

Public Function area() As Single
    area = m_Length * m_Height
End Function