Reputation: 3250
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?
Upvotes: 1
Views: 508
Reputation: 3250
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
Upvotes: 1