Search code examples
excelribbonvba

Enable/Disable Ribbon Controls Independently


I've been searching many times for a solution to this and the closest solution is Ron de Bruin example but it does not cover what I need.

I am trying to do is essentially 2 things

Example: I have 4 buttons.

Button1 on Group1 and tab1

Button2 on Group1 and tab1

Button3 on Group2 and tab2

Button4 on Group2 and tab2

  1. When the ribbon control "Button1" is clicked it will run some code and disable the "Button1" at the end.

  2. When the ribbon control "Button2" is clicked it will run some code and the check the "Button3" and "button4" and set the opposite properties.

If button3 was true, it becomes false.

If button4 was false, it becomes true.

Can you provide some guidance to solve this


Solution

  • Ok, all buttons have GetEnabled events, so when ribbon activates/updates - event fired! (simple).

    Callback function to this event looks like this:

    Sub Button_GetEnabled(control As IRibbonControl, ByRef enabled)
    '(enabled = true to enable)
        enabled = EnableButtons
    End Sub
    

    So lets start! In your module with callbacks functions you need a global (global to callbacks) boolean smth like EnableButtons.

    And when ribbon loads this code example fires setting flag to True:

    Private Sub OnRib_Load(ribbonUI As IRibbonUI)
        Set MyRibbonUI = ribbonUI
        EnableButtons = True
    End Sub
    

    And on each button you need callback for GetEnabled event described above.

    After that - all buttons are enabled! So what we can make here? Lets look on OnAction callback to your desired button:

    Sub Button_Click(control As IRibbonControl)
         EnableButtons = False
         MyRibbonUI.Invalidate
         'do some stuff - buttons disabled
         EnableButtons = True
         MyRibbonUI.Invalidate
    End Sub
    

    So Invalidate method "updates" all controls. You can try to InvalidateControl desired control (which is a more preferable way, than Invalidate, due to performance), but I think that more elegant way is to place callbacks and events only on buttons you want!

    So, finally, you need reference to ribbon, boolean flag, and _GetEnabled events.

    More here