VBA for adding command button and assigning macro

Ody

Board Regular
Joined
Oct 14, 2010
Messages
215
Whats the VBA for adding a command button and assigning a macro to it?

For example, I have a macro that adds new sheets to my workbook. I'd like to incorporate into that macro the step of adding a command button to the new sheet and assigning a macro to that button which hides the sheet.

I know the VBA for hiding sheets but I can't figure out how to add the button and assign the macro to it.

Thanks for any help!
 

Excel Facts

Enter current date or time
Ctrl+: enters current time. Ctrl+; enters current date. Use Ctrl+: Ctrl+; Enter for current date & time.
Whenever you're stuck with some code, it's always easiest to just use the built in macro recorder in Excel and then see what you get for code.

it's pretty straight forward, just put the screen coordinates for where to draw the button and what to set the action to and then select a worksheet cell so that the button is no longer selected in edit mode.

Code:
Sub AddButton()
    ActiveSheet.Buttons.Add(251.25, 39.75, 124.5, 42.75).Select
    Selection.OnAction = "StupidSub"
    Range("A1").Select
End Sub
 
Upvote 0
You can also do it without selecting:

ActiveSheet.Buttons.Add(251.25, 39.75, 124.5, 42.75).OnAction = "StupidSub"

:)
 
Upvote 0
Thanks for the info but when I add the code:

ActiveSheet.Buttons.Add(791.25, 6, 60.75, 15).OnAction = "Summary"

The button appears with the next sequential number for the control, i.e Button 18, Button 19, etc... and not titled "Summary".

Also, I'm not sure how I would create and assign a macro to the button that would hide the sheet. Any suggestions?

Thanks!
 
Upvote 0

Forum statistics

Threads
1,224,551
Messages
6,179,473
Members
452,915
Latest member
hannnahheileen

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