排序范围而不在电子表格中对其进行排序

Ale*_*lex 2 sorting excel vba excel-vba

问题是关于在VBA中排序数据.假设我有一个Range("A1:A10")我想按升序排序的.但是,我不想在我的电子表格中进行任何更改(因此所有计算都在VBA代码中进行).操作的输出应该是NewRange所有数字都被排序的位置.

对此问题有什么想法吗?

Ral*_*lph 7

这是一个非常简单的小例程,用于对二维数组进行排序,例如范围:

Option Base 1
Option Explicit

Function SortThisArray(aryToSort)

Dim i As Long
Dim j As Long
Dim strTemp As String

For i = LBound(aryToSort) To UBound(aryToSort) - 1
    For j = i + 1 To UBound(aryToSort)
        If aryToSort(i, 1) > aryToSort(j, 1) Then
            strTemp = aryToSort(i, 1)
            aryToSort(i, 1) = aryToSort(j, 1)
            aryToSort(j, 1) = strTemp
        End If
    Next j
Next i

SortThisArray = aryToSort

End Function
Run Code Online (Sandbox Code Playgroud)

如何使用此排序功能:

Sub tmpSO()

Dim aryToSort As Variant

aryToSort = Worksheets(1).Range("C3:D9").Value2    ' Input
aryToSort = SortThisArray(aryToSort)               ' sort it
Worksheets(1).Range("G3:H9").Value2 = aryToSort    ' Output

End Sub
Run Code Online (Sandbox Code Playgroud)

笔记:

  1. 这里排序的范围是Worksheet(1)在,Range("C3:D9")并且输出在同一张纸上Range("G3:H9")
  2. 范围将按升序排序.
  3. 范围将根据第一列(此处为C列)进行排序.如果您希望对另一列进行排序,则只需更改要排序的所有列aryToSort(i, 1)aryToSort(j, 1)列.例如,第2列:aryToSort(i, 2)aryToSort(j, 2).

更新:

如果您更喜欢使用上面的函数,那么这也可以这样:

Option Base 1
Option Explicit

Function SortThisArray(rngToSort As range)

Dim i As Long
Dim j As Long
Dim strTemp As String
Dim aryToSort As Variant

aryToSort = rngToSort.Value2
For i = LBound(aryToSort) To UBound(aryToSort) - 1
    For j = i + 1 To UBound(aryToSort)
        If aryToSort(i, 1) > aryToSort(j, 1) Then
            strTemp = aryToSort(i, 1)
            aryToSort(i, 1) = aryToSort(j, 1)
            aryToSort(j, 1) = strTemp
        End If
    Next j
Next i

SortThisArray = aryToSort

End Function
Run Code Online (Sandbox Code Playgroud)

这就是你如何使用这个功能:

在此输入图像描述