简体   繁体   中英

Excel VBA Reverse Selected Cells

I have the following bit in a macro in my workbook. It selects the last n=10 rows to set as the data source.

.lstDbase.RowSource = "Stencils!A" & iRow - 10 & ":R" & iRow

Am I able to reverse this selection without actually saving the reversed data?

Get Range Rows Reverse

Option Explicit

Sub PopulateRangeRowsReverse() ' ???
    
    Const fRow As Long = 2 ' ???
    Const rMaxOffset As Long = 10
    'Const iRow As Long = 11 ' ???
        
    'With ??? 
        
        Dim lrCount As Long: lrCount = iRow - fRow + 1
        If lrCount < 1 Then Exit Sub ' no data
        
        If lrCount > rMaxOffset Then lrCount = rMaxOffset
    
        Dim rg As Range
        Set rg = ThisWorkbook.Worksheets("Stencils") _
            .Rows(iRow - lrCount + 1).Columns("A:R").Resize(lrCount)
    
        Dim Data As Variant: Data = GetRangeRowsReverse(rg)
    
        With .lstDbase
            .Clear
            .ColumnCount = rg.Columns.Count
            .List = Data
        End With

    'End With

End Sub

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose:      Returns the reversed rows of a range in a 2D one-based array.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function GetRangeRowsReverse( _
    ByVal rg As Range) _
As Variant
    Const ProcName As String = "GetRangeRowsReverse"
    On Error GoTo ClearError
    
    Dim sData As Variant
    Dim rCount As Long
    Dim cCount As Long
    
    With rg
        rCount = .Rows.Count
        cCount = .Columns.Count
        If rCount + cCount = 2 Then
            ReDim sData(1 To 1, 1 To 1): sData(1, 1) = .Value
        Else
            sData = .Value
        End If
    End With
    
    Dim dData As Variant: ReDim dData(1 To rCount, 1 To cCount)
    
    Dim r As Long
    Dim c As Long
    
    For r = 1 To rCount
        For c = 1 To cCount
            dData(r, c) = sData(rCount, c)
        Next c
        rCount = rCount - 1
    Next r
    
    GetRangeRowsReverse = dData
    
ProcExit:
    Exit Function
ClearError:
    Debug.Print "'" & ProcName & "' Run-time error '" _
        & Err.Number & "':" & vbLf & "    " & Err.Description
    Resume ProcExit
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