【问题标题】:Excel vba: Class sub: Wrong number of arguments or invalid property assignment on vbaExcel vba:子类:vba 上的参数数量错误或属性分配无效
【发布时间】:2017-09-19 13:27:11
【问题描述】:

我有一个类 State 和其中的一些子类,它以 Scripting.Dictionary 作为参数。但是,当我尝试在那里传递字典时,出现wrong number of arguments or invalid property assignment 错误。我不知道出了什么问题。

'Sub insite State class
Sub addSecondItems(itemsDict As Object)
    MsgBox ("start addSecondItems")
End Sub

Sub test()
Dim stateCopy As State
Set stateCopy = New State
...
Dim dict1 As Object
Set dict1 = CreateObject("Scripting.Dictionary")
stateCopy.addSecondItems (dict1)  'error here
...
End Sub

同时

Sub testPetDict()

    Dim petDict As Object
    Set petDict = CreateObject("Scripting.Dictionary")
    Call readPetDict(petDict)

End Sub

Sub readPetDict(petDict As Object)
        Dim year As Integer
        For year = 2014 To 2017
            MsgBox (year & ". " & petDict(year))
        Next
End Sub

工作正常。

这里可能有什么问题以及为什么第二种情况有效,而第一种情况却失败了?

【问题讨论】:

  • 去掉括号:stateCopy.addSecondItems dict1或使用Call
  • 通过使用括号,您强制对象按值传递,因此错误。
  • @Rory 谢谢好心人!你把我从不可逆转的绝望中拯救了出来!你可以发布一个答案,我会批准它。
  • @Kostas 字典按值传递有什么问题?我不需要编辑它什么的。
  • 您不能通过值传递对象,只能通过引用传递。按值传递意味着创建并传递一个副本,而通过引用,只传递对对象的引用。

标签: vba excel


【解决方案1】:

你应该去掉括号:

stateCopy.addSecondItems dict1

或使用Call

Call stateCopy.addSecondItems(dict1)

否则方括号会尝试通过调用其默认属性Item 将字典强制转换为一个值,该属性需要一个参数,因此会出现错误消息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多