我创建了一个VBA UDF,它接收用户在Excel电子表格中选择的范围。例如, = MyFunction(A1:A5)。
我的问题是:我是否可以对此范围内的单元格值进行排序,而无需在每个单元格上循环,然后重新创建变量?
我尝试了下面的方法,但它不起作用:
MyVariableName.Sort 1, xlAscending
提前致谢,
温德尔
答案 0 :(得分:0)
假设只选择了一列,您可以将这些值放入数组中并对数组进行冒泡排序。
Function MyUDF(rng as range)
Dim vals() as variant
redim vals(rng.rows.count - 1)
for each cell in rng
vals(x) = cell.value
x = x + 1
next cell
'your code
End Function
Sub BubbleSort(list() As Variant)
' Sorts an array using bubble sort algorithm
Dim first As Integer, last As Long
Dim i As Long, j As Long
Dim temp As Long
first = LBound(list)
last = UBound(list)
For i = first To last - 1
For j = i + 1 To last
If list(i) > list(j) Then
temp = list(j)
list(j) = list(i)
list(i) = temp
End If
Next j
Next i
End Sub
vals数组将按升序排序。