vba-类

1.基本使用

' 长方体的类Cuboid
Private are
Private hig
 
Property Get area()
    area = are
End Property

Property Get high()
    high = hig
End Property

Function volume()
    volume = area * high
End Function

Function init(area, high)
    are = area
    hig = high
End Function

基本使用

Public Sub classt()
Dim cuboid As New cuboid
Call cuboid.init(2, 4)

MsgBox cuboid.volume
End Sub

2 .传递的数组

Private Type Taller
    length As Long
    wide As Long
End Type

Private tall() As Taller
Private count

Function init(arr)
    tallify arr
End Function

Function perimeter()
    For i = 1 To count
        perimeter = tall(i).length + tall(i).wide * 2
    Next
End Function

Private Function tallify(arr) As Variant  '这个方法用来包裹传进来的数组参数,如果数组内部结构有变动,我们只需要再这一个地方进行更改。
    For i = 1 To UBound(arr, 1)
        ReDim Preserve tall(0 To i)
        tall(i).length = arr(i, 1)
        tall(i).wide = arr(i, 2)
    Next
    count = i - 1
End Function

具体使用

Public Sub classt2()
Dim cuboid2 As New cuboid2
Dim arr(1 To 2, 1 To 2) As Long
arr(1, 1) = 1
arr(1, 2) = 2
arr(2, 1) = 3
arr(2, 2) = 4
 
Call cuboid2.init(arr) ''

MsgBox cuboid2.perimeter
End Sub

3.一个方法内职责过多,拆解:

Function perimeters()
    For i = 1 To count
        perimeter tall(i)
    Next
End Function

Private Function perimeter(tall As Taller)
    perimeter = tall.length + tall.wide * 2
End Function

 

posted @ 2023-08-10 17:06  vba是最好的语言  阅读(67)  评论(0编辑  收藏  举报