简体   繁体   中英

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:

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? 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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