2

Is it possible to have multipe buttons, lets say 'Button 1' and 'Button 2' run the same VBA code but yield a different result based on the button that was pressed?

For instance when I press button 1 I want it to go to a website, load data and put it on to Sheet 1. But when I press button 2, it goes to the same site and loads it to Sheet 2.

I know I can have multiple instances of the same VBA code (with different names) however I am hoping to simplify the code and prevent it from being overly complicated.

Luuklag
  • 3,897
  • 11
  • 38
  • 57
user1664305
  • 181
  • 7
  • 18
  • 1
    Related [How to call a macro from a button and pass arguments](http://stackoverflow.com/questions/29858176/how-to-call-a-macro-from-a-button-and-pass-arguments) and then just pass an argument to test with an if statement or other control statement – LinkBerest Feb 02 '16 at 04:46

3 Answers3

5

If you are using a Forms button you can assign the same macro and use Application.Caller to return the name/id of the calling button.

Sub Test()
MsgBox Application.Caller & " was pressed"
End Sub
brettdj
  • 54,857
  • 16
  • 114
  • 177
4

Create one sub to do the work and pass the sheetname as an argument to that sub. I did it with a string variable, but you can do it with a worksheet variable as well.

   Sub Button1_Click()

      LoadWebsiteToSheet "Sheet1"

   End Sub

   Sub Button2_Click()

      LoadWebsiteToSheet "Sheet2"

   End Sub

   Sub LoadWebsiteToSheet(sName as String) 

        '... code to load website to Worksheets(sName)

   End Sub
Scott Holtzman
  • 27,099
  • 5
  • 37
  • 72
0

I was leaning more towards brettdj's solution as well

If you assign the same macro to many buttons, you will get different results based on the button name.

You could name the button to the sheet you wanted. Practice with this. Add several buttons and assign this code to them. Click each button to see what happens.

Sub GetButtonName()
    Dim Btn As String

    Btn = ActiveSheet.Shapes(Application.Caller).Name
    MsgBox Btn

End Sub
Davesexcel
  • 6,896
  • 2
  • 27
  • 42