2016-02-16 45 views
2

在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 
+0

是否有原因,功能無法作出**公衆**? – Jeeped

+0

'''MyReturnValue = Application.Run(「Module2.MyFunctionInAnotherModule」)'''? – dee

回答

0

你需要你的價值迴歸的東西。 嘗試xyz = Module2.MyFunctionInAnotherModule

編輯:對不起,您還需要從您的功能中刪除私人。

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

感謝您的回覆,Sam。不幸的是從功能中刪除「私人」沒有奏效。相同的編譯錯誤。 –

+0

有趣。我能夠毫無問題地稱呼它。你有沒有嘗試用xyz = Module2.MyFunctionInAnotherModule調用它?即刪除Application.Run和引號。 –

相關問題