VBA:参数不可选

我正在尝试第一次在VBA中收集一些collections。 我打算使用这个集合来打开多个报表并运行相同的代码,这就是为什么我想把它们放到一个集合中。 (如果还有更好的方法,请告诉我。)


我的集合制作function(返回集合?):

Function CollectReports() As Collection Dim reports As New Collection reports.Add Item:="plant1", Key:="0" reports.Add Item:="plant2", Key:="1" reports.Add Item:="plant3", Key:="2" reports.Add Item:="plant4", Key:="3" TestCollection (reports) End Function 

我的collectionstesting小组:

 Sub TestCollection(reports As Collection) Dim x As Variant For Each x In reports MsgBox (x) Next End Sub 

我最初有副作为Sub TestCollection(ByRef reports) ,这是我一直在使用其他方法,需要从另一种方法昏暗。


我的问题是,当我尝试debugging我的CollectReports()函数时,我得到一个Argument not optional错误


如果你感觉真的很慷慨,这里是我打算使用这个集合的代码块 – 是一个集合最好的方法来做到这一点?

 Sub VlookupMGCCode(ByRef reports) Dim lastrow As Integer Dim wRange As Range Dim blankRange As Range Dim x As Variant lastrow = Cells(Rows.count, "A").End(xlUp).Row Set wRange = Range("$T$7:$T$" & lastrow) 'a single column to vlookup CollectReports For Each x in CollectReports 'deffinately an error here Set blankRange = wRange.SpecialCells(xlCellTypeBlanks) blankRange.Formula = "=VLOOKUP(RC[-18],'[" & x & "]Sheet1'!C1:C31,31,FALSE)" With blankRange .FillDown .Copy .PasteSpecial Paste:=xlPasteValues, SkipBlanks:=False End With Next End Sub 

我还没有尝试运行VlookupMGCCode()子,但作为集合是需要的,所以我不知道会出现什么样的错误,但我很有信心,我试图使用CollectReports返回的集合的方式是错的。


非常感谢您的帮助和时间!

有关何时使用括号的解释,请参阅此答案 。

你有几个问题:

  1. 这条线需要改变:

    TestCollection (reports)

    要么

    Call TestCollection (reports)

    要么

    TestCollection reports

  2. 您的CollectReports函数缺less分配集合的代码行。 您需要在该函数结束之前添加此行:

    Set CollectReports = reports

我相信错误报告是误导性的,你实际上得到TestCollection(报告)的错误,你不需要在调用子时brakcets。 请尝试删除这个和反馈,如果它的工作

 Function CollectReports() As Collection Dim reports As New Collection reports.Add Item:="plant1", Key:="0" reports.Add Item:="plant2", Key:="1" reports.Add Item:="plant3", Key:="2" reports.Add Item:="plant4", Key:="3" TestCollection reports End Function 

做错事情的方式是错误的

 Function CollectReports(reports As Collection) As Collection reports.Add Item:="plant1", Key:="0" reports.Add Item:="plant2", Key:="1" reports.Add Item:="plant3", Key:="2" reports.Add Item:="plant4", Key:="3" End Function Sub TestCollection() Dim reports As New Collection CollectReports reports Dim x As Variant For Each x In reports MsgBox (x) Next End Sub 

至于你的其他代码,我还没有testing过

 CollectReports For Each x in CollectReports 'deffinately an error here 

改成

 CollectReports reports For Each x In reports 'deffinately an error here