Trigger Event in Excel VBA when Row or Column is hidden

假如想象 提交于 2020-11-28 02:58:42

问题


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 is hidden in a particular sheet.

Is that possible?

Thanks in advance


回答1:


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


来源:https://stackoverflow.com/questions/24777074/trigger-event-in-excel-vba-when-row-or-column-is-hidden

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!