Collection.Add:参数数量错误或属性分配无效

时间:2017-09-11 12:14:10

标签: excel vba excel-vba

我有一个创建Collection并在其中添加Collection的子。但是在循环中添加第一个集合时出现Wrong number of arguments or invalid property assignment错误:

Sub testState()
    Dim stateCopy As State
    Set stateCopy = New State
    stateCopy.setStateName="some name"
    stateCopy.storeBudgetWorkbooks
    stateCopy.storeBudgetDatas  'error on this line
End Sub

Sub storeBudgetDatas()  'inside a class named State
 ...
  Dim year As Integer
  Dim i As Integer
  i = 1
  For year = 2014 To 2017
      Set budgetWorkbook = 
          ExcelApp.Application.Workbooks.Open(budgetWorkbooks(i))
      MsgBox ("still here")  'this message appears

      allBudgetItems.Add getBudgetData(budgetWorkbook, year) 'this line is likely to cause problems


      MsgBox ("and here")  'this message doesn't appear
      budgetWorkbook.Close
      i = i + 1
  Next
End Sub

Function getBudgetData(budgetWorkbook As Workbook, year As Integer)
  ...
  Dim budgetItems As Collection
  Set budgetItems = getBudgetItems(year)
  ... 'setting attributes
  getBudgetData = budgetItems(year)
End Function

Function getBudgetItems(year As Integer)
  ...
  Dim resultCollection As Collection
  Set resultCollection = New Collection
  Dim itemCopy As Item
  Dim i As Integer
  For i = LBound(budgetItemNames) To UBound(budgetItemNames)
      Set itemCopy = New Item
      ... 'setting attributes
      resultCollection.Add itemCopy
  Next

  Set getBudgetItems = resultCollection
End Function

我不确定这里有什么问题。 getBudgetItems返回一个集合。 getBudgetData也会返回一个集合。我尝试添加/删除括号但无济于事。

2 个答案:

答案 0 :(得分:1)

想出来。应该有getBudgetData = budgetItems(year)而不是{{1}}。

答案 1 :(得分:1)

由于您没有向我们展示代码的所有相关部分,我能做的最好的事情就是猜测您错过了Set

Function getBudgetData(budgetWorkbook As Workbook, year As Integer)
  ...
  Dim budgetItems As Collection
  Set budgetItems = getBudgetItems(year)
  ... 'setting attributes
  Set getBudgetData = budgetItems(year) ' Need Set here
End Function