Create and add macro in to an object

whcmelvin

Board Regular
Joined
Jul 27, 2011
Messages
82
Hi, how do i create an object and assign marco to the object automatically using VBA codes? is it possible?
 

Excel Facts

Can you AutoAverage in Excel?
There is a drop-down next to the AutoSum symbol. Open the drop-down to choose AVERAGE, COUNT, MAX, or MIN
I recorded macro and it showed me the code below.
ActiveSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", Link:=False _
, DisplayAsIcon:=False, Left:=382.5, Top:=105.75, Width:=97.5, Height _
:=43.5).Select

_______________________________________________________________

What is did when i start recording is to create a button and double click the button to put msgbox"hi"
 
Upvote 0
Assuming that the macro you want to trigger is Macro1, put this as the next line of the code --
Code:
    Selection.OnAction = "Macro1"

Denis
 
Upvote 0
They gave me an error msg.
Run time error 1004
unable to set on action property of the OLEOject Class
I already had a marco1 in my modules
 
Upvote 0
You do not assign macros to ActiveX buttons. Try recording a macro while adding a Forms button to the sheet - they do have an OnAction property.
 
Upvote 0
You should get something like...

Code:
Sub ButtonPlusCode()
    ActiveSheet.Buttons.Add(158.25, 43.5, 75.75, 24).Select
    Selection.OnAction = "SomeMacro"
End Sub

Denis
 
Upvote 0
Hi

I think it is a good idea to name an object when you create it. It makes it easier to access it later.

Code:
Sub ButtonPlusCode()
Dim bt As Button
 
    Set bt = ActiveSheet.Buttons.Add(158.25, 43.5, 75.75, 24)
    bt.Name = "MyButton"
    bt.OnAction = "SomeMacro"
End Sub
 
Upvote 0

Forum statistics

Threads
1,224,525
Messages
6,179,317
Members
452,905
Latest member
deadwings

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