VBA 从模块调用工作表中的 SUB
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33831691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA call a SUB in a Sheet from module
提问by user3614882
I am trying to call a Sub I defined inside a Sheet, from a Module.
我正在尝试从模块调用我在 Sheet 中定义的 Sub。
The code I use in my Module (which happens to be inside a Sub):
我在我的模块中使用的代码(恰好在一个 Sub 中):
CallByName Worksheets("Sheet_name"), "Sub_name", vbMethod
But Excel does not execute the Sub. The Module and Sheet are inside the same workbook.
但 Excel 不执行 Sub。模块和工作表位于同一个工作簿中。
回答by Estevam Garcia
You need to set your function to Publicas shown below
您需要将您的功能设置Public为如下所示
Sheet1:
表 1:
Public Sub test()
MsgBox "Got here!"
End Sub
Module:
模块:
Sub callTest()
With Sheet1
Call .test
End With
End Sub
回答by Sam
If it's in the same project and of Publicscope - just use the name of the sub.
如果它在同一个项目和Public范围内 - 只需使用子的名称。
If it's in a another workbook, use Application.Run()
如果它在另一个工作簿中,请使用 Application.Run()
1.
1.
Sub Foo()
Bar '// Runs Sub Bar()
End Sub
Sub Bar()
MsgBox "I got called!"
End Sub
2.
2.
Sub Foo()
Application.Run "MyOtherWorkbook.xlsm!Bar"
End Sub
回答by Mohammad ElNesr
From any module or sheet (that has a code),
if you have a sub called Button1_click()in "Sheet12" and you want to call it from other module or sheet.
just type
从任何模块或工作表(具有代码),如果您有一个Button1_click()在“ Sheet12”中调用的子,并且您想从其他模块或工作表调用它。只需输入
call Sheets("Sheet12").Button1_click 'Without parenthesis
回答by Mike Syracuse
for me, I had to change the Sheet Sub Procedure from Private to Public for the Call to work.
对我来说,我必须将 Sheet Sub Procedure 从 Private 更改为 Public 才能使 Call 工作。
Call Worksheets("Sheet_name").Sub_name
In my case:
就我而言:
Call Worksheets("Sheet 20").CommandButton1_Click

