【问题标题】:Compiler error when calling function in other module在其他模块中调用函数时编译器错误
【发布时间】:2016-02-16 07:06:51
【问题描述】:

在 Excel 的 VBA 宏中,我试图从另一个模块中的一个模块调用一个函数。

我能够成功调用另一个模块中的函数...但前提是我忽略了函数的返回值。

当我尝试调用另一个模块中的函数并保存返回值时 (MyReturnValue = Application.Run "Module2.MyFunctionInAnotherModule"),我收到编译器错误:“预期:语句结束”。

显然我在该语句的语法中遇到了问题,但我一直无法找到正确的语法。

模块 1:

Public Sub WhatGives()
Dim MyReturnValue As String

    ' Calling a subroutine in another module works
    Application.Run "Module2.MySub"

    MyReturnValue = MyFunctionInThisModule
    MsgBox ("MyFunctionInThisModule( ) returned:  " & MyReturnValue)

    ' Calling a function in another module works if
    ' I discard the return value of the function
    Application.Run "Module2.MyFunctionInAnotherModule"

    ' But calling a function and saving its return
    ' value doesn't work. When I uncomment the following
    ' statements, the second one results in the
    ' compiler error: "Expected: end of statement"
    'Dim MyReturnValue As String
    'MyReturnValue = Application.Run "Module2.MyFunctionInAnotherModule"
    'MsgBox("MyFunctionInAnotherModule( ) returned:  " & MyReturnValue)

End Sub

Private Function MyFunctionInThisModule()
    MsgBox ("MyFunctionInThisModule() invoked")
    MyFunctionInThisModule = "Return value from MyFunctionInThisModule"
End Function

模块 2:

Private Sub MySub()
    MsgBox ("MySub( ) invoked")
End Sub

Private Function MyFunctionInAnotherModule() As String
    MsgBox ("MyFunctionInAnotherModule( ) invoked")
    MyFunctionInAnotherModule = "Return value from MyFunctionInAnotherModule"
End Function

【问题讨论】:

  • 功能不能Public有什么原因吗?
  • MyReturnValue = Application.Run ("Module2.MyFunctionInAnotherModule")?

标签: vba excel office-2010


【解决方案1】:

你需要将你的价值归还给某物。 试试xyz = Module2.MyFunctionInAnotherModule

编辑:抱歉,您还需要从您的函数中删除 Private。

Function MyFunctionInAnotherModule() As String
    MsgBox ("MyFunctionInAnotherModule( ) invoked")
    MyFunctionInAnotherModule = "Return value from MyFunctionInAnotherModule"
End Function

【讨论】:

  • 感谢您的回复,山姆。不幸的是,从函数中删除“私人”不起作用。同样的编译器错误。
  • 有趣。我可以毫无问题地调用它。您是否尝试使用 xyz = Module2.MyFunctionInAnotherModule 调用它?即删除 Application.Run 和引号。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-12
  • 2021-11-23
  • 2017-08-10
  • 2021-10-28
相关资源
最近更新 更多