簡體   English   中英

確定從宏中單擊了哪個功能區控件(MS Word VBA)

[英]Identify which ribbon control was clicked from a macro (MS Word VBA)

我有幾個宏,它們幾乎都在做相同的事情:每個宏都打開一個單獨的文件。 我通過自定義功能區上的控件激活了它們。 但是,與其擁有幾個看起來像這樣的宏:

ChangeFileOpenDirectory SeriesPath
Documents.Open FileName:="Doc1.docx", _
    ConfirmConversions:=False, ReadOnly:=False, AddToRecentFiles:=False, _
    PasswordDocument:=Password$, PasswordTemplate:="", Revert:=False, _
    WritePasswordDocument:="", WritePasswordTemplate:="", Format:= _
    wdOpenFormatAuto, XMLTransform:=""

但是只更改了文件名,我希望有一個宏可以根據單擊的功能區元素打開任何一個文檔。 問題是,我需要知道單擊的功能區元素的ID。 我曾經瀏覽過幾個建議使用IRibbonUI.ID屬性的網站,但是當我嘗試這樣做時,我從Word中收到一條錯誤消息:“運行時錯誤91:對象變量或未設置塊變量。”

這是我的功能區導出的XML代碼的示例:

<mso:button idQ="x1:Open_00_1_549FAC6" label="00" imageMso="BlackAndWhiteDontShow" onAction="Open_00" visible="true"/>
<mso:button idQ="x1:Open_01_10_549FAC6" label="01" imageMso="AppointmentColor0" onAction="Open_01" visible="true"/>
<mso:button idQ="x1:Open_02_9_549FAC6" label="02" imageMso="AppointmentColor1" onAction="Open_02" visible="true"/>
<mso:button idQ="x1:Open_03_8_549FAC6" label="03" imageMso="AppointmentColor2" onAction="Open_03" visible="true"/>

有人知道我在做什么錯嗎?

首先,請原諒任何語法錯誤,這些答案在psuedo vba / xml中。

1)我建議使用功能區控制對象的id參數來確定被調用者,而不要使用其他函數。 您可以將它們重命名為更干凈的名稱,例如:

idQ="x1:Open_00" label="00" ... onAction="Open_OnAction"
idQ="x1:Open_01" label="01" ... onAction="Open_OnAction"

2)然后,您可以根據ID進行“解析”,或者僅對整個ID進行case / switch語句

Sub Open_OnAction(control As IRibbonControl)
    Dim filename As String
    Select Case control.id
        Case "x1:Open_00"
            filename = "somefilename00.xml"
        Case "x1:Open_01"
            filename = "somefilename01.xml"
    End Select

    'The rest of your code here
End Sub

*注意:如果您想更加精致,可以將文件名(通過XML)放入ID中,甚至不使用case語句,然后將其解析出來。 例如:

idQ="Open_myfilenamepathhere" ... onAction="Open_OnAction"

Sub Open_OnAction(control As IRibbonControl)
    Dim filename As String

    'This splits the control into multiple array elements based on delimeter of "_", then grabs the 2nd element (since the array's first element is 0)
    filename = Split(control.id,"_")(1)

    'The rest of your code here
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM