简体   繁体   English

在vba中按升序排序,最后一行可变

[英]Sort by Ascending Order in vba with Variable Last Row

I am having a hard time analyzing the problem in my code. 我很难分析我的代码中的问题。 I need to sort ColumnE by ascending order but the problem is the rows that should not be included in the sorting was also sorted. 我需要按升序对ColumnE进行排序,但问题是排序中不应该包括的行也已排序。

在此处输入图片说明

The highlighted in yellow should not be included in the sorting process. 黄色突出显示的颜色不应包含在排序过程中。 I need to start the sorting in row3. 我需要在row3中开始排序。

Here is my code: 这是我的代码:

        'sort by ascending order
        wsRD.Columns("C:E").Sort key1:=wsRD.Range("E1"), _
        order1:=xlAscending, Header:=xlYes

Can anyone tell me what's wrong in my code? 谁能告诉我我的代码有什么问题吗? Appreciate your help. 感谢您的帮助。

Thank you. 谢谢。

Your selection contains 2 header rows. 您的选择包含2个标题行。 You can either merge these headers, or set the range in your code as below (change the 9999 as needed): 您可以合并这些标题,也可以在代码中如下设置范围(根据需要更改9999):

    'sort by ascending order
    wsRD.Range("C2:E9999").Sort key1:=wsRD.Range("E2"), _
    order1:=xlAscending, Header:=xlYes

The header in the example consists of two rows. 示例中的标题由两行组成。 And the Header:=xlYes expects only the first row to be a header, thus the second line is taken as part of the values to be sorted. 并且Header:=xlYes期望仅第一行是标题,因此第二行被视为要排序的值的一部分。

To fix it, use Range("C1:E" & lastRow5).Sort key1:=Range("E2"), order1:=xlAscending, Header:=xlYes , which takes the lastRow of the fifth column of the ActiveSheet with lastRow(ActiveSheet.Name, 5) . 要解决此问题,请使用Range("C1:E" & lastRow5).Sort key1:=Range("E2"), order1:=xlAscending, Header:=xlYes ,它将ActiveSheet第五列的lastRow(ActiveSheet.Name, 5)lastRow(ActiveSheet.Name, 5)

The whole solution: 整个解决方案:

Sub TestMe()

    Dim lastRow5 As Long
    lastRow5 = lastRow(ActiveSheet.Name, 5)
    Range("C1:E" & lastRow5).Sort key1:=Range("E2"), order1:=xlAscending, Header:=xlYes

End Sub

Function lastRow(wsName As String, Optional columnToCheck As Long = 1) As Long

    Dim ws As Worksheet
    Set ws = Worksheets(wsName)
    lastRow = ws.Cells(ws.Rows.Count, columnToCheck).End(xlUp).Row

End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM