title: Trying to sort excel range by two columns using c#
body: <p>I have a range in excel that I need to sort by two columns. The data will always range from Column A to Column AA and I need to first sort it by column A (which is a date column, so oldest to newest), then by column F (numeric column, smallest to highest). The number of rows will vary.</p>
  
  <p>Here is what I've got so far, keep in mind I'm relatively new to c#.</p>
  
  <pre><code>         Excel.Worksheet JobDataSheet = new Excel.Worksheet();
  
           foreach (Excel.Worksheet tmpSheet in Globals.ThisAddIn.Application.ActiveWorkbook.Sheets)
           {
               if (tmpSheet.Name == "Job Labour" || tmpSheet.Name == "Job Materials" || tmpSheet.Name == "Job Cost Report")
               {
                   tmpSheet.Delete();
               }
               if (tmpSheet.Name == "Job Cost")
                   JobDataSheet = tmpSheet;
           }
  
  
           int MyCount = JobDataSheet.UsedRange.Rows.Count;
  
            //Sort Collection by Date &amp; Ref Line
           Excel.Range tempRange = JobDataSheet.get_Range("A2:A" + MyCount);
           Excel.Range tempRange2 = JobDataSheet.get_Range("F2:F" + MyCount);
  
           JobDataSheet.Sort.SortFields.Clear();
           JobDataSheet.Sort.SortFields.Add(tempRange // First Key
                                             ,Excel.XlSortOn.xlSortOnValues
                                             ,Excel.XlSortOrder.xlAscending
                                             ,Type.Missing
                                             ,Excel.XlSortDataOption.xlSortNormal);
           JobDataSheet.Sort.SortFields.Add(tempRange2 // Second Key
                                             , Excel.XlSortOn.xlSortOnValues
                                             , Excel.XlSortOrder.xlAscending
                                             , Type.Missing
                                             , Excel.XlSortDataOption.xlSortNormal);
  
           JobDataSheet.Sort.SetRange(JobDataSheet.get_Range("A1:AA" + MyCount));
           JobDataSheet.Sort.Header = Excel.XlYesNoGuess.xlYes;
           JobDataSheet.Sort.MatchCase = false;
           JobDataSheet.Sort.Orientation = Excel.XlSortOrientation.xlSortRows;
           JobDataSheet.Sort.SortMethod = Excel.XlSortMethod.xlPinYin;
           JobDataSheet.Sort.Apply();
  </code></pre>
  
  <p>At the <code>JobDataSheet.Sort.Apply();</code> line excel throws <code>"The sort reference is not valid. Make sure that it's within the data you want to sort, and the first Sort By box isn't in the same or blank."</code></p>