vba Selection.OnAction = "工作簿名称!宏名称"

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18685929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 23:12:49  来源:igfitidea点击:

Selection.OnAction = "Workbookname!Macroname"

vbaexcel-vbaexcel

提问by user1283776

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”

假设您有两个工作簿,一个称为“MyWorkbook”,另一个称为“PatchMyWorkbook”。两个工作簿都在保存时打开。“PatchMyWorkbook”有一个宏来添加按钮并将“MyWorkbook”的现有宏分配给“MyWorkbook” “MyWorkbook”中的现有宏称为“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”

这不会在“PatchMyWorkbook”代码执行时导致错误,但新添加的按钮宏将指向“'PatchMyWorkbook'!PrintPage”而不仅仅是“MyWorkbook”的“PrintPage”

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?

问题:如何为跨工作簿的宏按钮设置“OnAction”,以便宏指向当前工作簿而不是创建宏的工作簿?

回答by Kazimierz Jawor

In my opinion .OnAction propertyshould be set in this way:

在我看来.OnAction property应该这样设置:

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).

也对我来说有效(Excel 2010)。

回答by first_answer

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

您需要包含PrintPage定义的工作表或模块的名称。

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.Nameare important.

周围的单引号MyWbk.Name很重要。

回答by user3294649

A quick and easy way is :

一种快速简便的方法是:

workbooks("name_of_workbook").Worksheets("name_of_sheet").Shapes("name_of_button").OnAction = "name_of_your_macro"

Just substitute the different "name_of_..." by your names.

只需用您的名字替换不同的“name_of_...”。

Does it work?

它有效吗?