Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selection.OnAction = "Workbookname!Macroname"

Tags:

excel

vba

Say you have two Workbooks one called “MyWorkbook” and the other called “PatchMyWorkbook”. Both workbooks are open at the save time. The “PatchMyWorkbook” has a macro to add a button and assign an existing macro of “MyWorkbook” to “MyWorkbook” The existing macro in “MyWorkbook” is called “PrintPage”

Windows(“MyWorkbook”).Activate  
Sheets("Sheet1").Activate
ActiveSheet.Buttons.Add(665.25, 43.5, 89.25, 45).Select
Selection.OnAction = "PrintPage"

This does not cause an error while the “PatchMyWorkbook” code executes but the newly added buttons macro will point to “’PatchMyWorkbook’!PrintPage” rather than just “PrintPage” of the “MyWorkbook”

Question: How can you set the “OnAction” for a macro button across workbooks so that the macro will point to the current workbook not the workbook from where the macro has been created?

like image 925
user1283776 Avatar asked Oct 20 '25 19:10

user1283776


2 Answers

In my opinion .OnAction property should be set in this way:

Selection.OnAction = myWbk.Name & "!PrintPage"

By the way, the idea from your comment (changed a bit below):

Selection.OnAction = "'" & myWbk.Name & "'" & "!" & "PrintPage"

is working for me as well (Excel 2010).

like image 73
Kazimierz Jawor Avatar answered Oct 22 '25 12:10

Kazimierz Jawor


You need to include the name of the sheet or module where PrintPage is defined.

Dim methodName As String
With <module or sheet where 'PrintPage' is defined>
    methodName = "'" & MyWbk.Name & "'!" & .CodeName & ".PrintPage"
End With
MyWbk.Sheets("Sheet1").Shapes("ButtonName").OnAction = methodName

The single quotes surrounding MyWbk.Name are important.

like image 39
first_answer Avatar answered Oct 22 '25 12:10

first_answer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!