title: Excel VBA sort a range
body: <p>I've written a macro that opens a CSV file containing new data, copies the contents (minus the header row), and pastes it into the main workbook. Now I need it to also sort the entire dataset (all data in the main sheet) by sample number, given in column A. I've tried 2 different methods:</p>
  
  <pre><code>Set rData = ThisWorkbook.Sheets("Data").Range("A1")
  Set rData = Range(rData, rData.End(xlDown).Offset(0, 4))
  rData.Sort Key1:=Range("A:A"), Order1:=xlAscending, Header:=xlYes  'Debug points here
  </code></pre>
  
  <p>This method returns run-time error 1004: "The sort reference is invalid."</p>
  
  <pre><code>Set rData = ThisWorkbook.Sheets("Data").Range("A1")
  Set rData = Range(rData, rData.End(xlDown).Offset(0, 4))
  ThisWorkbook.Sheets("Data").Sort.SortFields.Clear    'Debug points here
  ThisWorkbook.Sheets("Data").Sort.SortFields.Add Key:=Range( _
      "A:A"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
      xlSortNormal
  With ThisWorkbook.Sheets("Data").Sort
      .SetRange Range(rData)
      .Header = xlYes
      .MatchCase = False
      .Orientation = xlTopToBottom
      .SortMethod = xlPinYin
      .Apply
  End With
  </code></pre>
  
  <p>This method returns run-time error 9: "Subscript out of range."</p>