0

enter image description hereI am running an Excel Macro from vb.net for sorting range of data and I receive this error as in the attached image

enter image description here

My Code is

Dim ws As Worksheet
Dim lastRow As Long
Set ws = Worksheets("Result_T10")
lastRow = Worksheets("Result_T10").Range("C2" & Cells(Rows.count, "C").End(xlUp).Row)
with ws
ws.Range("C2" & lastRow).Sort Key1:=Range("C2" & lastRow), Order1:=xlAscending, Header:=xlYes
End With

So What is wrong in the code?

Thanks, Regards

Moheb Labib

Meho2016
  • 25
  • 5

2 Answers2

1

You are treating the last row as an entire range and adding to the range. You need to isolate the last row as a row number then create the range.

Dim ws As Worksheet
Dim lastRow As Long
Set ws = Worksheets("Result_T10")
lastRow = ws.Cells(Rows.count, "C").End(xlUp).Row
with ws
ws.Range("C2:C" & lastRow).Sort Key1:=Range("C2"), Order1:=xlAscending, Header:=xlYes
End With
Darrell H
  • 1,876
  • 1
  • 9
  • 14
0

Wrong in this line

lastRow = Worksheets("Result_T10").Range("C2" & Cells(Rows.count, "C").End(xlUp).Row)

As lastRow is Long data type it can store number value only. Your current line returning a range not row. So add .row at the end of line like below.

lastRow = Worksheets("Result_T10").Range("C2" & Cells(Rows.count, "C").End(xlUp).Row).Row

You can simplify this line with

lastRow = ws.Cells(Rows.count, "C").End(xlUp).Row
Harun24hr
  • 30,391
  • 4
  • 21
  • 36