C# Office.Interop.Excel How do I loop through the AutoFilter'd returned rows?

Alvord, Timothy 276 Reputation points
2023-01-30T17:01:16.05+00:00

I have created the following AutoFilter:

excelRange = excelWorksheet.get_Range("G1");
excelRange.AutoFilter(Field: 7, Criteria1: "Part Number");
excelRange.AutoFilter(Field: 7, Criteria1: ">A*", Operator: Microsoft.Office.Interop.Excel.XlAutoFilterOperator.xlAnd);
excelRange.AutoFilter(Field: 4, Criteria1: "<2023-01-01", Operator: Microsoft.Office.Interop.Excel.XlAutoFilterOperator.xlAnd);

This reduced the rows down to a number let's say 935. How do I loop through the 935 rows produced by the AutoFilter?





Microsoft 365 and Office Excel For business Windows
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Jack J Jun 25,296 Reputation points
    2023-01-31T02:41:07.36+00:00

    @Alvord, Timothy, Welcome to Microsoft Q&A, you could try to use Range.SpecialCells(XlCellType, Object) Method to get filtered rows.

    Here is a code example you could refer to.

    Excel.Application app=new Excel.Application();
    Excel.Workbook workbook = app.Workbooks.Open("test.xlsx");
    Excel.Worksheet worksheet = workbook.Worksheets[1];
    Excel.Range visibleCells = worksheet.UsedRange.SpecialCells(
                                   Excel.XlCellType.xlCellTypeVisible,
                                   Type.Missing);                                                                       
     Excel.Range visibleCells = worksheet.UsedRange.SpecialCells(
                                   Excel.XlCellType.xlCellTypeVisible,
                                   Type.Missing);
                foreach (Excel.Range area in visibleCells.Areas)
                {
                    foreach (Excel.Range row in area.Rows)
                    {
                        if (row.Row!=935)
                        {
                            Console.WriteLine(row.Row);
                        }
                        else
                        {
                            break;
                        }
                        
                    }
                }
                workbook.Close();
    
    

    Based on my test. it could produce the correct row's count.


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.