I'm creating formated worksheets with an Excel VBA application and I would like to add programmatically add a button to each worksheet when created. This button must have a macro attached to it, which display the average of the values in a certain range in a special cell, and change the background color of this cell depending on the value of the average. Is it possible to this, and if yes, how can I do it ?
1 Answer
You can add the Button like this or example:
ActiveSheet.Buttons.Add(52.5, 7.5, 173.25, 41.25).Select 'Arguments are coordinates
Selection.OnAction = "Button_Click"
Now make sure the Button_Click sub has the logic you want.
9 Comments
otus
Ok, this seems to be fine, but apparently the macros are disabled in the worksheet I generate and the code inside the Button_Click sub doesn't execute when I click on the button, how can I programmatically enable the macros for each worksheet I create ?
AnalystCave.com
You can't programmatically enable macros. What would be the point in this as a security feature :). You need to go to options and lower your level of security to enable macros by default.
Rory
@otus what's the error message and in which module is the
button_click code located?AnalystCave.com
@Rory my bad then. Strange though.
Rory
@AnalystCave.com Not really - you have to have already enabled macros to run the code that then enables code in the relevant workbook, so it's not really a security flaw. ;)
|