wrcathey
wrcathey

Reputation: 53

How to programatically find what has called a macro

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.

Is there a way do this?

Upvotes: 5

Views: 6809

Answers (2)

quantum285
quantum285

Reputation: 1032

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.

Upvotes: 3

Siddharth Rout
Siddharth Rout

Reputation: 149325

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 THIS if you want to take it to a different level. :)

Upvotes: 3

Related Questions