设置加速器以编程方式添加按钮

时间:2014-10-02 19:50:02

标签: vba excel-vba excel

我无法弄清楚我在这里做错了什么。我以编程方式向Excel工作表添加了一个按钮。我正在尝试分配加速键,但它没有被分配。相关代码是:

Sub addPrint(sht, Optional fromLeft, Optional fromTop)
If IsMissing(fromLeft) Then fromLeft = 180
If IsMissing(fromTop) Then fromTop = 10
    Set printbut = sht.Buttons.Add(fromLeft, fromTop, 50, 20)
    printbut.Name = "PrintButton"
    printbut.OnAction = "Sheet4.printButton"
    printbut.Characters.Text = "Print/PDF"
    printbut.Accelerator = "P"
End Sub

' P'没有加下划线,Alt-P什么都不做。

感谢。

1 个答案:

答案 0 :(得分:0)

这是添加ActiveX按钮的方法:

Sub addActiveXCommandButton(sht As Worksheet, Optional left As Single = 100, Optional top As Single = 100)

    Dim btn As OLEObject

    '
    'create Button
    '
    Set btn = ActiveSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", Link:=False, _
                    DisplayAsIcon:=False, left:=left, top:=top, _
                    Width:=105.75, Height:=36)

    Debug.Print TypeName(btn)           ' this returns OLEObject as a wrapper of the CommandButton
    Debug.Print TypeName(btn.Object)    ' this returns CommandButton - the activeX-Object

    '
    ' access the CommandButton-Object and set the Accelerator value
    '
    btn.Object.Accelerator = "B"

End Sub

但是,我不确定,可以访问加速器按钮。在测试时,可以使用Alt键访问Accelerator Button。 我使用带有按钮和application.onKey定义的解决方案,它们都访问相同的过程。