运行时错误1004排序参考无效?

时间:2020-08-27 10:58:54

标签: excel vba vb.net sorting

enter image description here我正在从vb.net运行Excel宏以对数据范围进行排序,并且如附件中的图像所示,我收到此错误

enter image description here

我的代码是

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

那么代码有什么问题?

谢谢!

Moheb Labib

2 个答案:

答案 0 :(得分:0)

您将最后一行视为整个范围并添加到该范围。您需要将最后一行隔离为行号,然后创建范围。

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

答案 1 :(得分:0)

此行错误

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

由于lastRowLong数据类型,因此它只能存储数字值。您当前的行返回一个范围而不是行。因此,像下面这样在行尾添加.row

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

您可以通过以下方式简化此行

lastRow = ws.Cells(Rows.count, "C").End(xlUp).Row