简体   繁体   English

如何使用宏创建按钮以运行宏

[英]How to create a button using a macro to run a macro

I recorded a macro to help me run code I have written. 我记录了一个宏来帮助我运行编写的代码。 The code itself works. 代码本身有效。 However, I cannot seem to create a button that will run the code. 但是,我似乎无法创建一个可以运行代码的按钮。

With Summary 
        .Buttons.Add(1039.8, 60.6, 66.6, 28.8).Select
        Selection.OnAction = "PERSONAL.XLSB!Clear_Error"
        Selection.Characters.Text = "Clear"
        With Selection.Characters(Start:=1, Length:=11).Font
            .Name = "Calibri"
            .FontStyle = "Regular"
            .Size = 11

End With

Summary is the worksheet.The button is created but the button itself does nothing. 摘要是工作表。按钮已创建,但按钮本身不执行任何操作。 Also, When I tried manually assigning the macro to the button, the code still does not work. 另外,当我尝试手动将宏分配给按钮时,代码仍然不起作用。 However, when I run the code, it runs smoothly. 但是,当我运行代码时,它运行平稳。

Thanks, 谢谢,

G G

You could try to first Set the button to a variable declared as Button . 您可以尝试首先Set按钮Set为声明为Button的变量。

Option Explicit

Sub Test()

    Dim Btn As Button, Summary As Worksheet
    Set Summary = ThisWorkbook.Worksheets(1)
    Set Btn = Summary.Buttons.Add(1039.8, 60.6, 66.6, 28.8)
    With Btn
        .OnAction = "PERSONAL.XLSB!Clear_Error"
        .Characters.Text = "Clear"
        With .Characters(Start:=1, Length:=11).Font
            .Name = "Calibri"
            .FontStyle = "Regular"
            .Size = 11
        End With
    End With

End Sub

I personally (as well as most of the rest of the VBA community) have a strong dislike of .Select , .Selection , .Activate , etc. So that's usually the first thing I try to get rid of when I help with issues, then move from there. 我个人(以及大多数VBA社区)对.Select.Selection.Activate等非常不喜欢。因此,这通常是我在解决问题时首先要摆脱的第一件事,然后从那里移动。

Note: I did set Summary to worksheet 1, so that may need to be modified for your needs. 注意:我确实将Summary设置为工作表1,因此可能需要根据您的需要进行修改。

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

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