PDA

View Full Version : [SOLVED:] VBA creating, activating command buttons



cjt
12-01-2014, 12:24 PM
I am attempting to make a macro which creates a button, then assigns that button a name and caption and allows me to use that name to assign the button a macro all within VBA. I have been able to create the button but I either have the proper name and caption and can't click it with this code:

ActiveSheet.Buttons.Add(Left:=48, Top:=250, Width:=96.75, Height:=44.25).Select Selection.Name = "CheckFlags"
Selection.Caption = "Check For Flags"

Or else I get a clickable button without the name or caption and cannot find a way to assign them with this code:

ActiveSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", Left:=48, Top:=250, Width:=97, Height:= _
45).Select



Also once I have a working button how can I assign the macro to it through VBA in such a way that when I run the code which creates the button the macro is immediately assigned to the newly created button?

Thank you in advance for your help!

mikerickson
12-01-2014, 06:39 PM
This will work to create a Forms menu command button

ActiveSheet.Buttons.Add(Left:=48, Top:=250, Width:=96.75, Height:=44.25).Name = "CheckFlags"
With ActiveSheet.Shapes(ActiveSheet.Shapes.Count)
.TextFrame.Characters.Text = "New Button"
.OnAction = "myMacro"
End With

cjt
12-04-2014, 10:01 AM
Thanks works great!

snb
12-04-2014, 01:51 PM
or

Sub M_snb_003()
With ActiveWorkbook.Sheets(1).Buttons.Add(48, 250, 66, 45)
.Name="interesting"
.Caption = "unexpected"
.OnAction = "Sheet1.M_snb_002"
End With
End Sub