VBA 添加按钮,设置标题并将其链接到方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8949641/
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 14:59:57  来源:igfitidea点击:

VBA Add button, set the caption and link it to a method

excelvba

提问by alyon2002

I want to add a button on a new worksheet, set the caption and link it to a method in a module. Any help would be appreciated. Thanks!

我想在新工作表上添加一个按钮,设置标题并将其链接到模块中的方法。任何帮助,将不胜感激。谢谢!

回答by GSerg

Dim b As Excel.Shape
Set b = ActiveSheet.Shapes.AddFormControl(xlButtonControl, 10, 10, 100, 100)
b.OnAction = "AMacro"
b.OLEFormat.Object.Text = "Run a macro"

回答by T I

Try this taken from http://www.mrexcel.com/forum/showthread.php?t=43637

试试这个取自http://www.mrexcel.com/forum/showthread.php?t=43637

Sub CreateButton()
    ActiveSheet.Buttons.Add(199.5, 20, 81, 36).Select
    Selection.Name = "New Button"
    Selection.OnAction = "CheckTotals"
    ActiveSheet.Shapes("New Button").Select
    Selection.Characters.Text = "Check Totals"
End Sub

Edit:GSerg's answer is admittedly better then this as this was just a quick copy and paste job for illustrative purposes. I will leave the answer up as a comparative against a better way to programme VBA and a small reference as to why you should avoid Selection. I'd imagine the code snippet would be something produced via the macro recorder and clearly this will never be optimal.

编辑:GSerg 的答案无疑比这更好,因为这只是用于说明目的的快速复制和粘贴工作。我将把答案留作与更好的 VBA 编程方式的比较,以及关于为什么应该避免Selection. 我想代码片段将是通过宏记录器生成的东西,显然这永远不会是最佳的。