如何将数组排序到范围

时间:2019-04-08 15:05:09

标签: excel vba

我在excel电子表格中有一个数字数组,我正在尝试使用用户定义的vba函数对所有数字进行排序(所有数字> 60),并且我想在同一excel表中将结果作为范围返回。

当我在excel中运行此函数时遇到值错误。我不太确定此错误是从哪里来的,因为我是VBA的新手。对于解决此问题的指导,我将非常感谢。

数组Excel

Column A
200
50
23
789

Function trial(number As Range)
    Dim cell As Range
    Dim savearray() As Variant
    Dim d As Long

    For Each cell In Range("a3:a6").Cells
        If cell.Value > 60 Then
            d = d + 1
            ReDim Preserve savearray(1 To d)
            savearray(1, d) = cell.Value
            trial = savearray
        End If
    Next cell
End Function

2 个答案:

答案 0 :(得分:0)

在您的Sub上需要做一些工作。但是,为了帮助您,下面是一种动态构建数组的方法:

d = 0
For Each cell In Range("A3:A1000")
    If cell.Value > 60 Then
        If d = 0 Then
            ReDim savearray(0 To 0)
        Else
            ReDim Preserve savearray(0 To UBound(savearray) + 1)
        End If
        savearray(d) = cell.Value
        d = d + 1
    End If
Next cell

答案 1 :(得分:0)

我觉得您可能想宁可返回排序后的数组,然后才将结果转换为Range


  1. 首先,我们创建一个Function对数组进行排序

    Private Function BubbleSort(ByRef from() As Variant) As Variant()
    
       Dim i As Integer, j As Integer
       Dim temp As Variant
    
       For i = LBound(from) To UBound(from) - 1
           For j = i + 1 To UBound(from)
               If from(i) < from(j) Then
                   temp = from(j)
                   from(j) = from(i)
                   from(i) = temp
               End If
           Next j
       Next i
    
       BubbleSort = from ' returns sorted array
    
    End Function
    
  2. 然后我们创建一个简单的“ Range替换程序”

    Private Sub replace_with_sorted(ByVal which As Range)
    
       Dim arr() As Variant
       arr = Application.Transpose(which)
       arr = BubbleSort(arr)
    
       which = Application.Transpose(arr)
    
    End Sub
    
  3. 因此调用的外观如下:

    Private Sub test()
        replace_with_sorted Range("A1:A4")
    End Sub
    

这当然会产生预期的结果:

enter image description here


编辑:刚注意到您只想对大于60的值进行排序。 在这种情况下,只需使用大于60的值填充数组并使用同一应用程序即可。

Private Sub test()
  Dim arr() as Variant: arr = Application.Transpose(Range("A1:A4"))
  Dim above60() as Variant
  Dim i as Integer, j as Integer: j = 0

  For i = LBound(arr) To UBound(arr)
         If arr(i) > 60 Then
            ReDim Preserve above60(j)
            above60(j) = arr(i)
            j = j + 1
         End If
  Next i

  ReDim arr()
  arr = BubbleSort(above60) 
  ' returns sorted array, do whatever u want with it _
   (place it in whatever range u want, not defined in ur question)


End Sub