简体   繁体   English

Excel VSTO-访问AutoFilter的数组条件会引发异常

[英]Excel VSTO - accessing AutoFilter's Array Criteria throws exceptions

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. 我正在使用Excel中的C#VSTO项目,该项目需要保存当前的自动筛选器信息,并在某些表更新后重新应用筛选器。 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. 基本上,代码myCriteria = someFilter.Criteria2 (返回用于简单文本过滤器的字符串)现在抛出COM异常。

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. 有关此问题的MSDN文档( http://msdn.microsoft.com/zh-cn/office/microsoft.office.interop.excel.filter_members(v=office.14) )根本没有帮助。

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. 我想通过代码获得“ Criteria2”部分。

Any ideas are highly appreciated! 任何想法都受到高度赞赏!

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. 剩下的是过滤条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM