问题
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.
- Modify the Ribbon XML (if it's present): You need to be able to modify the Ribbon's
customUI14.xml
(for Excel 2010) orcustomUI.xml
(for Excel 2007). - 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).
- 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.
- 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:
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