简体   繁体   English

使用 VBA 的板载排序功能

[英]Using VBA's onboard sort function

I want to sort an array and since I am lazy I wanted to use the onboard sort function of EXCEL/VBA.我想对数组进行排序,因为我很懒,所以想使用 EXCEL/VBA 的板载排序功能。 According to the official MS Office support worksheetfunctions.sort should also be working with arrays, see here .根据官方 MS Office 支持 worksheetfunctions.sort 也应该使用数组,请参见此处 Here is my first try.这是我的第一次尝试。

Sub sorting()

Dim myArray1() As Double
Dim myArray2() As Double
ReDim myArray1(1 To 5)

myArray1(1) = 0.221157
myArray1(2) = -0.147981
myArray1(3) = -2.07119
myArray1(4) = 4.434685
myArray1(5) = -2.706056

myArray2 = WorksheetFunction.Sort(myArray1, 1, 1)

End Sub

This produces a type mismatch error, therefore I have adjusted my code to这会产生类型不匹配错误,因此我已将代码调整为

Sub sorting()

Dim myArray1() As Variant
Dim myArray2() As Variant
ReDim myArray1(1 To 5)

myArray1(1) = 0.221157
myArray1(2) = -0.147981
myArray1(3) = -2.07119
myArray1(4) = 4.434685
myArray1(5) = -2.706056

myArray2 = WorksheetFunction.Sort(myArray1, 1, 1)

End Sub  

The code runs without any error, but myArray2 is not sorted, it is just a copy of myArray1.代码运行没有任何错误,但是 myArray2 没有排序,它只是 myArray1 的一个副本。

I am using:我在用:

Microsoft® Excel® for Microsoft 365 MSO (Version 2204 Build 16.0.15128.20128) 32-bit Microsoft® Excel® for Microsoft 365 MSO(版本 2204 Build 16.0.15128.20128)32 位

Your problem is connected to the fourth function parameter...您的问题与第四个函数参数有关...

It is Optional , but its makes sorting by rows if not used ( False ).它是Optional ,但如果不使用( False ),它会按行排序。 Since you try sorting a 1D array not having any row, it does not sort anything.由于您尝试对没有任何行的一维数组进行排序,因此它不会对任何内容进行排序。

You should use:你应该使用:

   myArray2 = WorksheetFunction.Sort(myArray1, 1, 1, True)

Such an array has only columns...这样的数组只有列......

Note : The array to be filtered must be declared As Variant , in the same way it is needed to be declared when it will be loaded from a range.注意:要过滤的数组必须声明As Variant ,与从范围加载时需要声明的方式相同。 The above function does not accept such an array declared As Double , As Long ...上面的函数不接受这样的数组声明As DoubleAs Long ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM