简体   繁体   English

VBA代码为控件按钮分配名称,而不是让excel生成从数字派生的按钮名称

[英]VBA Code to assign names to control buttons instead of letting excel generate button names derived from numbers

This seems to be a basic question, but I can not figure out how to do this and I cant find the answer on the internet. 这似乎是一个基本问题,但是我不知道该怎么做,也无法在互联网上找到答案。 I have a workbook that I want to generate a series of command buttons for. 我有一个工作簿,我想为其生成一系列命令按钮。 Each command button is tied to a certain macro. 每个命令按钮都绑定到某个宏。 I would really like to have the buttons name themselves according to what they will calculate instead of just generating names such as "button 346". 我真的很想让按钮根据它们将要计算的名称来命名,而不只是生成诸如“按钮346”之类的名称。 However, I cant figure out how to make this happen. 但是,我不知道如何做到这一点。 While this is not crucial to my code, it would make the user experience more friendly, and therefore I figure its worth asking if anyone knows what to do. 尽管这对我的代码并不重要,但它会使用户体验更友好,因此我认为值得一问的是,是否有人知道该怎么做。

Here is a sample of my code. 这是我的代码示例。 I would like to name the button ,"Add Investment" 我想将按钮命名为“添加投资”

Selection.OnAction = "AB_Investment"
ActiveSheet.Buttons.Add(2676.75, 90, 131.25, 14.25).Select

Please let me know if I can clarify any further. 如果可以进一步说明,请告诉我。 I am still a amateur at vba coding, so I am sorry if this is a super basic question. 我仍然是vba编码的业余爱好者,所以如果这是一个非常基本的问题,我感到抱歉。

Thanks, 谢谢,

Josiah 约西亚

If you want, you can take it further. 如果需要,可以更进一步。 As always, it's recommended to stay away from Select and Selection , but using a referenced object to your created button. 与往常一样,建议您远离SelectSelection ,但要对创建的按钮使用引用的对象。

Sub AddButton()

Dim Btn As Object

Set Btn = ActiveSheet.Buttons.Add(2676.75, 90, 131.25, 14.25)

With Btn
    .Caption = "Add Investments"
    ' you can modify other properties as well
    .Font.Bold = True
End With

End Sub

Consider: 考虑:

Sub ButtonNamer()
    ActiveSheet.Buttons.Add(2676.75, 90, 131.25, 14.25).Select
    Selection.Name = "Add Investment"
End Sub

在此处输入图片说明

Note: 注意:

The Name of the button is not the same as its Caption . 按钮的名称与其标题不同

Since you're worrying about making "the user experience more friendly" I guess you are referring to the text shown over the button, which calls for its Caption property: 由于您担心要使“用户体验变得更加友好”,所以我猜您指的是按钮上方显示的文本 ,该文本需要其Caption属性:

ActiveSheet.Buttons.Add(2676.75, 90, 131.25, 14.25).Select
Selection.Caption = "Add Investments"

which can be also shortened down to: 也可以缩短为:

ActiveSheet.Buttons.Add(2676.75, 90, 131.25, 14.25).Caption = "Add Investments"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM