简体   繁体   English

Excel VSTO自动筛选器无法正常工作吗?

[英]Excel VSTO Autofilter not working right?

I'm working on a Excel VSTO project with Office & VS 2010. I have the code to get a range but I can't seem to get the Autofilter to work right. 我正在使用Office&VS 2010进行Excel VSTO项目。我具有获得范围的代码,但似乎无法使自动筛选器正常工作。 Heres the code I have so far: 这是我到目前为止的代码:

Excel.Workbook wb = (Excel.Workbook)Globals.ThisWorkbook.InnerObject;
Excel.Name rngN = wb.Names.Item("MyNamedRange", System.Type.Missing, System.Type.Missing);
Excel.Range rng = rngN.RefersToRange;
int allRows = rng.Rows.Count;
rng.AutoFilter(8, "ST", Microsoft.Office.Interop.Excel.XlAutoFilterOperator.xlOr, System.Type.Missing, null);
int filteredRows = rng.Rows.Count;

However, in this example, the row counts are identical and my range is not filtered at all - Im referring to the variables allRows and filteredRows above. 但是,在此示例中,行计数是相同的,并且我的范围完全没有过滤-Im引用了上面的变量allRowsfilteredRows So I'm either not implementing the filter correctly and or my filter statement is wrong. 所以我要么没有正确实现过滤器,要么我的过滤器语句错误。 My filter line: 我的过滤器行:

rng.AutoFilter(8, "ST", Microsoft.Office.Interop.Excel.XlAutoFilterOperator.xlOr, System.Type.Missing, null);

So my understanding is that this line would look for all matches of "ST" in the 8th field. 因此,我的理解是,该行将在第8个字段中查找“ ST”的所有匹配项。 Is that not correct? 那不正确吗? Why are my record counts the same? 为什么我的记录数相同?

In answer to the second part of your question, getting the number of filtered rows is tricky. 在回答问题的第二部分时,获取过滤后的行数非常棘手。 rng.Rows.Count will return the original number of rows, not the filtered number. rng.Rows.Count将返回原始行数,而不是过滤后的行数。

You can use an expression like the following: 您可以使用如下表达式:

Evaluate("=SUBTOTAL(3," & Range("A:A").Address & ")-1")

which you can store in an integer - you may have to cast the result. 您可以将其存储为整数-您可能必须强制转换结果。

3 represents the COUNTA function (excluding the filtered rows) and I'm subtracting 1 to exclude the header row. 3代表COUNTA函数(不包括过滤的行),我要减去1以排除标题行。 Increase this number if there are other occupied cells in the column. 如果列中还有其他占用的单元格,请增加此数字。

You could store this formula temporarily in a cell, but I believe it should return a result using Evaluate() . 您可以将此公式临时存储在单元格中,但是我相信它应该使用Evaluate()返回结果。

Added Read 添加阅读

rng.SpecialCells(xlCellTypeVisible).Count

before and after applying the filter to determine whether the filter worked. 在应用过滤器之前和之后确定过滤器是否正常工作。

There is useful information about Excel filtering at this MSDN link . 在此MSDN链接上有关于Excel筛选的有用信息。

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

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