问题
I am working on a C# VSTO project in Excel that needs to save the current AutoFilter information and re-apply the filter after some table update. I have managed to have it work on simple text and number filters. But it fails on Date Filters.
On a closer look, it seems when the filter Criteria is an Array, there is no way to access the criteria? Basically, the code myCriteria = someFilter.Criteria2
, which returns a string for simple text filters, throws a COM exception now.
The MSDN doc on this issue (http://msdn.microsoft.com/en-us/office/microsoft.office.interop.excel.filter_members(v=office.14)) is not helping at all.
I tried to record the filtering in Macro, and here is the recorded code for filtering a Date column to October:
ActiveSheet.Range("$C$1:$C$6").AutoFilter Field:=1, _
Operator:=xlFilterValues, _
Criteria2:=Array(1, "10/31/2013")
The "Criteria2" part is what I want to get via code.
Any ideas are highly appreciated!
回答1:
A tiny trick!
Say the filter was applied manually. At the time you apply a filter to a column, your only options are the items in the column. Once the filter has been applied, the only visible cells in the column are the ones selected by the filter.
Thus you can run a loop down the column, collecting the visible cells. Then remove duplicates with a Collection or Dictionary. What remain are the filter criteria.
来源:https://stackoverflow.com/questions/19779230/excel-vsto-accessing-autofilters-array-criteria-throws-exceptions