Sort range without sorting it in a spreadsheet

后端 未结 3 767
温柔的废话
温柔的废话 2020-12-04 01:00

Question is about sorting data in VBA. Suppose I have a Range(\"A1:A10\") which I want to sort in ascending order. However, I do not want any changes in my spre

3条回答
  •  囚心锁ツ
    2020-12-04 01:07

    Here I am submitting slightly different sort routine.It sorts the 2nd column first then 1st column.

    Function BubbleSort(TempArray() As Variant, SortIndex As Long)
    
        Dim blnNoSwaps As Boolean
    
        Dim lngItem As Long
    
        Dim vntTemp(1 To 2) As Variant
    
        Dim lngCol As Long
    
        Do
    
            blnNoSwaps = True
    
            For lngItem = LBound(TempArray) To UBound(TempArray) - 1
    
                If TempArray(lngItem, SortIndex) > TempArray(lngItem + 1, SortIndex) Then
    
                    blnNoSwaps = False
    
                    For lngCol = 1 To 2
    
                        vntTemp(lngCol) = TempArray(lngItem, lngCol)
    
                        TempArray(lngItem, lngCol) = TempArray(lngItem + 1, lngCol)
    
                        TempArray(lngItem + 1, lngCol) = vntTemp(lngCol)
    
                    Next
    
                End If
    
            Next
    
        Loop While Not blnNoSwaps
    
    End Function
    
    
    
    Sub Test()
    
        Dim vntData() As Variant
    
        vntData = range("C3:D9")
    
        BubbleSort vntData, 2
    
        BubbleSort vntData, 1
    
        range("G3:H9") = vntData
    
    End Sub
    

    Results obtained from this routine are shown below.

提交回复
热议问题