Copying a button from one sheet to automatically run code when copied to new sheet.

Ronanm

Board Regular
Joined
Nov 13, 2010
Messages
107
Hi I am struggling with getting a macro to run when I create a new button on a sheet. I assign the On Action to the button and the macro runs without debug, but... the OnAction doesn't run the Macro "Test".

The Button being copied to Sheet2 is on Sheet1, then the Macro should automatically run when the button is pasted to Sheet2.

Any ideas?

Code:
Sub Macro1()

    Sheets("Sheet1").Visible = xlSheetVisible
    Sheets("Sheet1").Select
On Error Resume Next
    ActiveSheet.Shapes.Range(Array("Button 1")).Select
  
    Selection.Copy
    
    Sheets("Sheet2").Select
    With ActiveSheet.Buttons.Add(500.5, 5.75, 90, 46.5)
        .Name = "New Button"
        .Size = 11
        .Bold = True
        .Characters.Text = "Run second Macro"
        .OnAction = "Test"
    End With
    ActiveSheet.Shapes.Range(Array("New Button")).Select
    
Sheets("Sheet1").Visible = xlSheetHidden
End Sub


Sub test()
    Sheets("Sheet2").Activate
    Cells(1, 1).Select
    MsgBox ("Macro finished, and in Cell A1")
End Sub

Thank you.
 

Excel Facts

Format cells as currency
Select range and press Ctrl+Shift+4 to format cells as currency. (Shift 4 is the $ sign).
If you are going to copy and paste the button, try this


Code:
Sub Macro1()


    Sheets("Sheet1").Visible = xlSheetVisible
    Sheets("Sheet1").Select
    ActiveSheet.Shapes.Range(Array("Button 1")).Select
  
    Selection.Copy
    Sheets("Sheet2").Select
    ActiveSheet.Paste
    
    With Selection
        .Name = "New Button"
        .OnAction = "Test"
    End With
    
    Application.Run ActiveSheet.Shapes("New Button").OnAction
    
    Sheets("Sheet1").Visible = xlSheetHidden
End Sub
 
Upvote 0
I'm glad to help you. Thanks for the feedback.
 
Upvote 0

Forum statistics

Threads
1,214,614
Messages
6,120,517
Members
448,968
Latest member
Ajax40

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top