C# Excel Automation: Retrieving rows after AutoFilter() with SpecialCells() does not seem to work properly

后端 未结 3 1536
耶瑟儿~
耶瑟儿~ 2021-01-13 02:55

First time poster here :). I\'m having the following trouble automating Excel 2010 from a WinForms C# application. My test table looks the following way:

Ind         


        
3条回答
  •  太阳男子
    2021-01-13 03:51

    OK, I solved my own problem, but I would like to share the solution because some other poor soul might struggle with the same problem someday. Basically, my first idea that the problem might be with the rows not being consecutive led me to the right answer. As long as all the filtered values are right under the first row in the table, the SpecialCells() method returns one single area, and so the filteredRange shows in its Value2 member all of the desired values (in the test case from above, all the "AAA") rows. If, however, the filtered rows are further down in the table, as is the case with "BBB", the SpecialCells() method returns multiple areas, in this case two - first area containing only the column names line, and the second area containing the three "BBB" rows. The solution is to iterate over all the areas in filteredRange and extract/manipulate the values from there:

            for (int areaId = 1; areaId <= filteredRange.Areas.Count; areaId++)
            {
                Excel.Range areaRange = filteredRange.Areas.get_Item(areaId);
                object[,] areaValues = areaRange.Value2;
                // Do something with the values here...
    

    So that's it. I hope that this helps someone else someday...

提交回复
热议问题