VBA:参数不是可选的

时间:2015-07-09 15:24:49

标签: excel vba excel-vba collections

我第一次尝试在VBA中搞砸了一些收藏品。我计划使用此集合打开多个报告并运行相同的代码,这就是我想将它们放入集合的原因。 (如果有更好的方法,请告诉我。)

我的收藏制作功能(返回收藏?):

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

我的收藏测试Sub:

Sub TestCollection(reports As Collection)

    Dim x As Variant

    For Each x In reports
        MsgBox (x)
    Next

End Sub

我原来将子Sub TestCollection(ByRef reports)作为我用于其他需要来自其他方法的Dim的方法。

我的问题是我尝试调试Argument not optional函数时出现CollectReports()错误

如果您感觉非常慷慨,那么我计划使用此系列的代码块是 - 这是一个最好的方法吗?

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() Sub,因为需要收藏,所以我不知道会出现什么错误,但我对这种方式非常有信心我试图使用CollectReports返回错误的集合。

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

3 个答案:

答案 0 :(得分:1)

我认为错误报告具有误导性, 你实际上是在TestCollection(Reports)中得到错误,你在调用sub时不需要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

答案 1 :(得分:1)

有关何时使用括号的说明,请参阅this answer

您有几个问题:

  1. 需要更改此行:

    TestCollection (reports)

    要么

    Call TestCollection (reports)

    TestCollection reports

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

    Set CollectReports = reports

答案 2 :(得分:0)

以错误的方式做事情

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

至于你的其他代码,我还没有测试过,只有

CollectReports

For Each x in CollectReports 'deffinately an error here

更改为

CollectReports reports

For Each x In reports 'deffinately an error here