在集合中使用集合作为属性(参数不是可选的)

时间:2018-01-19 12:28:32

标签: excel vba excel-vba class collections

我试图将一组日期用作类属性,并且遇到问题。从本质上讲,我希望在vacLocation中存储多个emp_vacDates,并将其输入employee.Vaca

使用Employee.Name

时没问题

我得到的错误是

  

编译错误:参数不是可选的

Vaca让声明

我的代码是:

Sub Vacation()
    Dim i As Integer
    Dim rowNum As Long: rowNum = 5
    Dim colNum As Long: colNum = 4
    Dim onePersonLoop As Range
    Dim nameLocation As Range
    Dim vacLocation As Range
    Dim emp_vacDates As Collection
    Dim emps As Collection
    Dim employee As EmployeeClass

    For i = 2 To 2
        With ActiveWorkbook.Worksheets(i)

            Set onePersonLoop = .Cells(rowNum, colNum).Offset(-1).End(xlToRight).Offset(, -2)
            Set emps = New Collection
            For rowNum = 5 To 5

                Set nameLocation = .Cells(rowNum, colNum).Offset(-1, -1).EntireRow.Cells(1, 2)
                Set employee = New EmployeeClass
                employee.Name = nameLocation.Value
                Set emp_vacDates = New Collection

                For colNum = 4 To 6

                    Set vacLocation = .Cells(rowNum, colNum).Offset(-3)
                    If .Cells(rowNum, colNum) = "v" Or .Cells(rowNum, colNum) = "V" Then
                        emp_vacDates.Add vacLocation.Value
                    End If
                Next colNum

                employee.Vaca = emp_vacDates
                emps.Add employee

                Debug.Print employee.Name
                Debug.Print employee.Vaca

            Next rowNum

        End With
    Next i
End Sub

我的EmployeeClass类模块设置如下

Option Explicit

Dim vName As String
Dim vVaca As Collection

Public Property Get Name() As String
    Name = vName
End Property

Public Property Let Name(nme As String)
    vName = nme
End Property

Public Property Get Vaca() As Collection
    Vaca = vVaca
End Property

Public Property Let Vaca(vcl As Collection)
    vVaca = vcl
End Property

2 个答案:

答案 0 :(得分:3)

收藏集应为Set。 像这样:

Public Property Get Vaca() As Collection
    Set Vaca = vVaca
End Property

Public Property Let Vaca(vcl As Collection)
    Set vVaca = vcl
End Property

此外,您不能只调试这样的集合:

Debug.Print employee.Vaca

尝试在那里做其他事情,例如:

Debug.Print employee.Vaca.Item(1)

或者编写一个函数,检查集合中是否有项目,如果没有项目,则打印0。像这样:

Public Function VacaToString(Optional index = 1) As String

    If Vaca.Count = 0 Then
        VacaToString = 0
    Else
        VacaToString = Vaca(index)
    End If

End Function

然后你可以像这样调试它:

Debug.Print employee.VacaToString

答案 1 :(得分:2)

vVacavcl都是Collection类型的对象。 对象必须使用set

Public Property Get Vaca() As Collection
    Set Vaca = vVaca
End Property

Public Property Let Vaca(vcl As Collection)
    Set vVaca = vcl
End Property