Quite a few times I was getting this question from my readers –
- How to associate a VBA code to a button?
- How to write a vba code which gets executed by clicking on a command button in excel vba.
- Add a button to trigger my macro
- and so on…
Here are 3 simple steps by which you can associate a code with a command button:
Note: These steps are common for all the ActiveX Controls added in excel sheet like Text box, Radio Button, Check box etc.
Add your command button as shown in below picture:
Double click on the Button (note: Before double clicking make sure that you are in design mode in excel macro as highlighted above)
You can right click on the command button and click on “View Code” as well
By default you will be taken to a screen as shown below.
In the above image as you can see in the right hand side there is a drop down which has all the events which can be triggered on this commandbutton like .”Click”, Double Click”, on focus etc. As you as select an event VBA screen will automatically take you to that event procedure syntax.
There between “Sub” and “End Sub” you can write your own code or you call call any other function which you have already defined.