简体   繁体   中英

Sorting a range of rows in ascending order between similar cell values in a column in Excel VBA

Since I am new to writing macros. I need assistance in writing a macro which sorts a range of rows between the cell values "TLA". Here is an example:

Column A   
  TLA  
   23
    6
   32
  TLA
  TLA
    5
   21
   16
   40
  TLA

I have tried modifying a macro which I got browsing from this forum.But, I am not able to select the rows. Any pointers or Assistance will be of great help for me. VB:

Sub Sort_column_TLA() 

    Dim r As Long 
    Application.ScreenUpdating = False 
    ActiveSheet.DisplayPageBreaks = False 
    r =Range("A"& ActiveSheet.Rows.Count).End(xlUp).Row 
    For r = r To 2 Step -1 

        Select Case Cells(r, 1) 
        Case "TLA" 
             'do nothing
        Case Else 
            Range(r & ":" & r ).Select 

             'Rows(r).Select
        End Select 
    Next r 
End Sub 

Your construct looks very strange:

r =Range("A"& ActiveSheet.Rows.Count).End(xlUp).Row  
For r = r To 2 Step -1 

I think it is more transparent if you have the counter run from up till down (specific reason to go the other way around?) Use another counter, eg. lCnt (as long). Hope it helps you on the way.

Set the range differently using for example

set oRange = thisworkbook.sheets("<Name>").usedrange    'Declare oRange as excel.range
for each oRow in oRange.rows   
    lCnt = lCnt + 1
    select case oRow.cells(lcnt, 1)
        case "TLA" 
        oRow.select 
        'etc... 
    end select
next oRange 

I see no issues with your code except that you are not actually sorting the values.
As far as selection is concerned, if you debug the code and run step by step you will see the row does get selected.

The following will sort all the values between "TLA" in ascending

Function a()
    Dim r, r2 As Long

    r2 = 0

    Application.ScreenUpdating = False
    ActiveSheet.DisplayPageBreaks = False
    r = Range("A" & ActiveSheet.Rows.Count).End(xlUp).Row
    For r = r To 1 Step -1

        If (Cells(r, 1) = "TLA") Then
            If (r2 <> 0) Then
                If (r2 - r >= 2) Then
                    With Range(r + 1 & ":" & r2)
                        .Sort Key1:=Range("A" & r + 1), _
                                Order1:=xlAscending, _
                                Orientation:=xlTopToBottom
                    End With
                End If
            End If
        r2 = r - 1
        End If

    Next r
End Function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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