Trigger Event in Excel VBA when Row or Column is hidden

前端 未结 1 2038
春和景丽
春和景丽 2021-01-07 14:20

Is there a way, to trigger an event (call a sub) in Excel VBA, when i manually hide a row/column?

I want the same row to be hidden in all following sheets, when it i

相关标签:
1条回答
  • 2021-01-07 14:52

    There is no direct event trigger to capture hiding or unhiding columns. There are clumsy workarounds, using formulae in cells but those feel like a kludge when using and not really flexible.

    However, there is an indirect way to capture this event if you use Excel 2007 or newer. This is neat and extremely flexible.

    1. Modify the Ribbon XML (if it's present): You need to be able to modify the Ribbon's customUI14.xml (for Excel 2010) or customUI.xml (for Excel 2007).
    2. Create the custom Ribbon UI XML file (if not present): You may use Ron De Bruin's excellent Custom UI Editor from http://www.rondebruin.nl/win/s2/win001.htm (which is also endorsed in quite a few official Microsoft examples).
    3. XML changes for capturing events: Open the Excel file in the Custom UI Editor and add the XML code as shown below. That will enable a column hide or unhide event to trigger a macro in your code.
    4. VBA code to execute your actions: Add the code listed below to take action once the event is captured.

    Reference: This excellent solution was provided by Andy Pope here (MSDN link).

    Custom XML code:

    <customUI  xmlns="http://schemas.microsoft.com/office/2006/01/customui" >
        <commands >
            <command 
                idMso="ColumnsHide"
                onAction="Column_Hide_Macro"/>
            <command 
                idMso="ColumnsUnhide"
                onAction="Column_UnHide_Macro"/>
        </commands >
    </customUI>
    

    Custom UI Editor screenshot: enter image description here

    VBA code:

    Sub Column_Hide_Macro(control As IRibbonControl, ByRef CancelDefault)
        MsgBox ("You have hidden a column")
    
        ' You may put your code here
        ' to check if your monitored row is hidden
    
        CancelDefault = False   ' This enables the default action to continue
    End Sub
    
    Sub Column_UnHide_Macro(control As IRibbonControl, ByRef CancelDefault)
        MsgBox ("You have unhidden a column")
    
        ' You may put your code here
        ' to check if your monitored row is unhidden
    
        CancelDefault = False   ' This enables the default action to continue
    End Sub
    
    0 讨论(0)
提交回复
热议问题