I want to add a button on a new worksheet, set the caption and link it to a method in a module. Any help would be appreciated. Thanks!
2 Answers
Dim b As Excel.Shape
Set b = ActiveSheet.Shapes.AddFormControl(xlButtonControl, 10, 10, 100, 100)
b.OnAction = "AMacro"
b.OLEFormat.Object.Text = "Run a macro"
4 Comments
alyon2002
This works to insert a button but when I click on the new button it doesn't run the macro, it selects the button and highlights the caption for editing, also it runs the macro when its created I only need it ran when it is clicked? What am I doing wrong
brettdj
@alyon2002 are you left clicking the button to run it, or right clicking which will bring up design mode?
brettdj
Gserg, I realised at some stage I accidentally downvoted this by mistake as I scrolled the page. I have edited your post code formatting to remedy this. My apologies
alyon2002
I was right clicking, turns out I needed to left click and exit text edit mode, this worked great thank you
Try this taken from http://www.mrexcel.com/forum/showthread.php?t=43637
Sub CreateButton()
ActiveSheet.Buttons.Add(199.5, 20, 81, 36).Select
Selection.Name = "New Button"
Selection.OnAction = "CheckTotals"
ActiveSheet.Shapes("New Button").Select
Selection.Characters.Text = "Check Totals"
End Sub
Edit: GSerg's answer is admittedly better then this as this was just a quick copy and paste job for illustrative purposes. I will leave the answer up as a comparative against a better way to programme VBA and a small reference as to why you should avoid Selection. I'd imagine the code snippet would be something produced via the macro recorder and clearly this will never be optimal.
4 Comments
GSerg
Selecting things in Excel for acting on them is evil.
brettdj
@Gserg Its certainly not optimal, but as its working code it didn't deserve the downvote (from whoever did that)
brettdj
@alyon2002 Primarily as it is unncessary but it slows code down. It can also cause errors, ie the object may not be directly selectable (the worksheet may be hidden), it may trigger other
Event driven code etc.alyon2002
@Tom, I tried your example it it worked after I put Character.Text before ("New Button").select, thanks for the help!