vba 如何以编程方式找到所谓的宏

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26635007/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 05:03:21  来源:igfitidea点击:

How to programatically find what has called a macro

excelexcel-vbavba

提问by wrcathey

I am trying to write a macro that has a portion that reacts differently depending on whether it is called directly from a button in the worksheet, or called indirectly from another macro. I also want to be able to have it react differently depending on which other macro has called it

我正在尝试编写一个宏,该宏的一部分根据是直接从工作表中的按钮调用还是从另一个宏间接调用而有不同的反应。我还希望能够让它根据其他宏调用它的方式做出不同的反应

In this case, if the macro is activated manually by the button or if it has been run by a particular other macro, it pops up a msgbox to let the user know that it has been completed successfully, but if the same macro is run by another macro, then I want to skip that step.

在这种情况下,如果宏是通过按钮手动激活的,或者它已经被特定的其他宏运行,它会弹出一个 msgbox 让用户知道它已成功完成,但如果相同的宏由另一个宏,那么我想跳过这一步。

Is there a way do this?

有没有办法做到这一点?

采纳答案by quantum285

You could do this by passing arguments to the subroutines. Here's a very basic example:

您可以通过将参数传递给子例程来做到这一点。这是一个非常基本的例子:

Sub test(number, displayMessage)
MsgBox ("The number is " & number)
If displayMessage Then MsgBox ("You ran the B sub")
End Sub

Sub aSub()
Call test(4, False)
End Sub

Sub bSub()
Call test(7, True)
End Sub

Try running both aSub and bSub. Hope this helped.

尝试同时运行 aSub 和 bSub。希望这有帮助。

回答by Siddharth Rout

Here is one way which will work for Shapes/Procedures

这是一种适用于形状/程序的方法

Dim SSub As String

Sub Sample()
    On Error Resume Next
    SSub = Application.Caller '<~~ Already suggested by @Socii
    On Error GoTo 0

    Debug.Print "This procedure was called by " & SSub
End Sub

Sub Example()
    SSub = "Example" '~~> (Also see the link below)
    Sample
End Sub

You may also want to read THISif you want to take it to a different level. :)

如果你想把它带到一个不同的层次,你可能还想阅读这个。:)