简体   繁体   English

在VBA中使用Excel的比较运算符?

[英]Using Excel's comparison operator in VBA?

I'm trying to figure out how I can use the same comparison operator that Excel uses in sorting a mix of alphanumeric values like the following: 我试图弄清楚如何使用与Excel相同的比较运算符来对字母数字值进行排序,如下所示:

0
9
34
51
123abc
15
a
a1b23c
i
z
34ui
10
d
1
12

When sorting this, this is the result: 排序时,结果如下:

0
1
9
10
12
15
34
51
123abc
34ui
a
a1b23c
d
i
z

Is it possible to use the comparison operator that Excel uses to get this result? 是否可以使用Excel用于获得此结果的比较运算符? Or is it necessary to create my own function for this? 还是有必要为此创建我自己的功能?

I just went ahead and created a comparison function with the same return values as StrComp() since it seems there isn't one already. 我只是继续创建了一个比较函数,该函数的返回值与StrComp()因为似乎还没有返回值。

Function ExcelCompare(ByVal str1 As String, ByVal str2) As Integer
    Dim isnum1 As Boolean
    Dim isnum2 As Boolean
    isnum1 = IsNumeric(str1)
    isnum2 = IsNumeric(str2)
    ExcelCompare = StrComp(str1, str2)
    If isnum1 And Not isnum2 Then
        ExcelCompare = -1
    ElseIf Not isnum1 And isnum2 Then
        ExcelCompare = 1
    ElseIf isnum1 And isnum2 Then
        Dim num1 As Double
        Dim num2 As Double
        num1 = CDbl(str1)
        num2 = CDbl(str2)
        If num1 = num2 Then
            ExcelCompare = 0
        ElseIf num1 < num2 Then
            ExcelCompare = -1
        Else
            ExcelCompare = 1
        End If
    End If
End Function

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

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