2014-10-02 57 views
2

我無法弄清楚我在這裏做錯了什麼。我以編程方式將一個按鈕添加到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

我不確定是否[this](http://www.vbforums.com/showthread.php?524674-RESOLVED-Excel-VBA-Button-Shortcut-Keys)會有所幫助,但我覺得有趣的是有帖子來自2008年的@SiddharthRout關於這個相同的主題 – mrbungle 2014-10-02 20:01:45

+0

查看@mrbungle給出的鏈接中的帖子6和7。問題是你正在創建一個表單控件而不是一個activeX按鈕。表單控件沒有'.Accelerator'屬性。 – 2014-10-02 21:03:46

+2

@mrbungle:自2005年以來,我一直在論壇發帖:P – 2014-10-02 21:04:06

回答

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鍵訪問加速器按鈕。 我使用一個解決方案,一個按鈕和一個application.onKey-定義,這兩個訪問相同的過程。

+0

謝謝。我最終關注了另一個問題及其工作。見下面的評論。 – 2014-10-03 13:02:39

+0

Abe Gold,您選擇的解決方案的鏈接是什麼? – DrMarbuse 2014-10-07 08:34:24

+0

http://stackoverflow.com/questions/3549586/how-to-create-a-dynamic-button-in-excel。那麼你可能會想看看http://stackoverflow.com/questions/10633387/programatically-inserting-click-event-code-for-dynamically-generated-label-not-w – 2014-10-07 19:34:17