Cornelius
Cornelius

Reputation: 1027

Using c# to filter excel range by three criteria in two separate columns

I'm filtering an excel range by three different criteria across two columns, column "B" is filter by matFilter1 and matFilter2 and column "AC" is filtered by matFitler3, the code I'm using is:

    //Filter Job Data Sheet for Material Transactions
    string matFilter1 = "I Job Issue";
    string matFilter2 = "W Job Withdrawal";
    string matFilter3 = "1";
    Excel.Range jobMatRange = JobDataSheet.UsedRange; //Define range of Job Material Sheet
    jobMatRange.AutoFilter(2, matFilter1, Excel.XlAutoFilterOperator.xlOr, matFilter2, true); //Apply matFilter1 and matFilter2 to column2 in range
    jobMatRange.AutoFilter(29, matFilter3, Excel.XlAutoFilterOperator.xlOr, Type.Missing, true); //Apply matFilter3 to column29 in range

Now this works fine, I'm just wondering if there is a better, cleaner way to do this. I'm new to c# and would like some input for a cleaner filter solution for a scenario like this.

Thanks in advance.

Upvotes: 1

Views: 5120

Answers (1)

MrBlue
MrBlue

Reputation: 840

If you were applying filters to more columns you could put the details in a collection and loop through it, but for only two it makes more sense to leave it as is. Readability is important and you can glance at that code an immediately understand that a filter is being applied to two columns.

Unless they're used elsewhere, you could always put the strings directly in the method calls.

jobMatRange.AutoFilter(2, "I Job Issue", Excel.XlAutoFilterOperator.xlOr, "W Job Withdrawal", true);
jobMatRange.AutoFilter(29, "1", Excel.XlAutoFilterOperator.xlOr, Type.Missing, true);

Upvotes: 1

Related Questions