【问题标题】:Call a method object with arguments that returns variable使用返回变量的参数调用方法对象
【发布时间】:2019-02-08 00:17:23
【问题描述】:

如何调用传递多个参数返回变量的方法?

我有一个名为 cExcelTable 的类。里面我有一个方法:

Public Function GetColumnNumberByColumnName(strColumnName As String)
    Dim resultColumnFound As Integer

    '... Here i have the code which find the right column
    '... then i return the result as an integer

    GetColumnNumberByColumnName = resutColumnFound
End Function

如何调用该方法并获取返回值?

我想要这个的等价物:

Dim myTable As New cExcelTable
    
Dim i as Integer
        
myTable.Workbook = "file.xlsx"
myTable.Sheet = "TestingSheet"
myTable.Table = "TabDatas"
'... And here is my bug that i don't know how to solve
i = myTable.GetColumnNumberByColumnName("TOTAL")

我知道对于没有返回值的方法,我必须使用 Call,但是返回值的方法呢?

【问题讨论】:

  • 看起来应该可以了。您遇到什么错误?
  • 尝试将函数的返回值设置为整数:Public Function GetColumnNumberByColumnName(strColumnName As String) As Integer 看看是否有帮助。
  • GetColumnNumberByColumnName中用于返回值的变量名拼写错误。应该是GetColumnNumberByColumnName = resultColumnFound
  • FWIW 你没有使用呼叫。如果事实上你不应该使用它,那么它已经过时了
  • 如果你使用 Option Explicit 你会发现这个错误

标签: excel vba object methods parameter-passing


【解决方案1】:

已解决

感谢 cmets 中的 PeterTDomenic 我在睡了一晚后发现我的错误不是方法的调用,而是我的方法中的两个变量拼写错误并添加它应该返回的类型

所以对于进入这篇文章的新人来说,答案是 在方法里面你应该使用这个

'Add the type the method it should return "As Integer"
Public Function nameOfTheMethod(parameterNumber1 As String) As Integer
    Dim resultColumnFound As Integer

    '... type your code
    '... then return the result with the correct spelling

    GetColumnNumberByColumnName = resultColumnFound
End Function

然后在你的代码中你可以像这样调用你的方法

Dim myObject As New cMyClass 'cMyClass  is the name of your class and myObject is the name of your object you are creating
Dim i as Integer

i = myObject.nameOfTheMethod("test")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-28
    • 2011-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多