尝试从具有参数的模块类中调用子方法时出现错误438

时间:2019-06-13 10:11:50

标签: excel vba oop object

我知道

  

错误438:对象不支持此属性或方法

当尝试运行以下代码时。你能帮我吗?

我的宏代码:

Sub test() 
   Dim upList As New ListRoot
   upList.msg 'this one works fine 

   Dim g As New Gradient
   upList.AppendRoot g 'line that raises the issue
End Sub

我的模块类代码:

Public Sub AppendRoot(grad As Gradient)
    If IsEmpty(content.content) Then
       Set content.content = grad
    Else
       content.Append (grad)
    End If
End Sub

Public Sub msg()
    MsgBox "HEY"
End Sub

我已经尝试过对方法的不同调用:

upList.AppendRoot(g) 
Call upList.AppendRoot(g) 

和上面引用的那个。没有办法。

1 个答案:

答案 0 :(得分:0)

请注意,必须在不带括号的情况下调用不返回值的子/函数:

content.Append grad

如果函数返回某个值,则必须添加括号

ReturnValue = content.Append(grad)

但是,如果将括号添加到不返回任何值的子/函数中,

content.Append (grad)

…强制变量grad提交ByVal,而ByRef是提交变量的标准方法。因此,通过在此处添加括号,您可以将ByRef更改为ByVal(您还可以看到函数/子名称与括号之间存在空格)。


示例:

Sub TestFunction(Param1, Param2, Param3) 'all 3 parameters are ByRef by default in VBA (not in VB.NET!)

End Sub

一些调用此函数的示例:

'submit 3 parameters ByRef, don't return anything
TestFunction Param1, Param2, Param3 
TestFunction(Param1, Param2, Param3) 'throws error

'submit 3 parameters ByRef, return a Value
ReturnValue = TestFunction(Param1, Param2, Param3) 
ReturnValue = TestFunction Param1, Param2, Param3   'throws error 

'submit parameters 1 and 3 ByVal and 2 ByRef, don't return anything
TestFunction (Param1), Param2, (Param3) 

'submit parameters 1 and 3 ByVal and 2 ByRef, return a Value
ReturnValue = TestFunction((Param1), Param2, (Param3)) 

虽然有3个参数,但如果在不应该添加括号的地方添加括号,则会引发错误,但仅使用一个参数会更加困难:

TestFunction Param1   'correct
TestFunction (Param1) 'this threw an error with 3 parameters, but does not throw an error 
                      'with one parameter instead it changes behavior ByRef to ByVal
ReturnValue = TestFunction(Param1) 'correct
ReturnValue = TestFunction Param1  'throws error