3

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!

1
  • 1
    what type of button, Forms or ActiveX? Commented Jan 21, 2012 at 1:17

2 Answers 2

9
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"
Sign up to request clarification or add additional context in comments.

4 Comments

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
@alyon2002 are you left clicking the button to run it, or right clicking which will bring up design mode?
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
I was right clicking, turns out I needed to left click and exit text edit mode, this worked great thank you
2

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

Selecting things in Excel for acting on them is evil.
@Gserg Its certainly not optimal, but as its working code it didn't deserve the downvote (from whoever did that)
@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.
@Tom, I tried your example it it worked after I put Character.Text before ("New Button").select, thanks for the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.