I maintain an Excel spreadsheet with data in multiple columns that can be sorted in various ways as each user deems useful. I set this up using macros with buttons on the sheets that do the various sorts
A user has requested the ability to sort on a column that has letter-number combinations, but sort by number only. The data is aircraft callsigns that contain 1 to 3 letters followed by 1 to 5 numbers. The user wants to sort by flight number with no regard to the registration letters.
I found a function that accomplishes this called "num()". I would like to use this function without altering the data in the column itself. Here's an example of what I'm shooting for:
Sub sortscenarionum()
'
' sortscenarionum Macro
' Sort Aircraft by FLIGHT NUMBER then RPO TIME
'
ActiveWorkbook.ActiveSheet.Sort.SortFields.Clear
ActiveWorkbook.ActiveSheet.Sort.SortFields.Add Key:=Range( _
"N11:N159"), SortOn:=num("N11:N159"), Order:=xlAscending, DataOption:= _
xlSortNormal
ActiveWorkbook.ActiveSheet.Sort.SortFields.Add Key:=Range( _
"I11:I159"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With ActiveWorkbook.ActiveSheet.Sort
.SetRange Range("B11:N159")
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
SendKeys "{ESC}"
End Sub
This fails with "Type mismatch". I have also tried SortOn:=num(xlSortValues) with the same negative results. I have no problem with moving the function into the macro itself, but I have no idea how to do that. Here's the function in case it's useful:
Function num(rng As Range) As String
Dim n As Integer
For n = 1 To Len(rng)
If Mid(rng, n, 1) Like "[0-9]" Then
num = num & Mid(rng, n, 1)
End If
Next n
End Function
Add a column to be used as a helper; populate then sort on the new column; delete the new column.
Sub sortscenarionum()
With ActiveWorkbook.ActiveSheet
.Columns("O").Insert
With .Range(.Cells(11, "B"), .Cells(.Rows.Count, "N").End(xlUp).Offset(0, 1))
.Columns(.Columns.Count).Formula = "=numsOnly(N11)"
.Columns(.Columns.Count).Value = .Columns(.Columns.Count).Value
.Sort Key1:=.Columns(.Columns.Count), Order1:=xlAscending, _
Key2:=.Columns(8), Order2:=xlAscending, _
Orientation:=xlTopToBottom, Header:=xlNo
End With
.Columns("O").Delete
End With
End Sub
Function numsOnly(str As String)
'with rgx as static, it only has to be created once
Static rgx As Object
If rgx Is Nothing Then
Set rgx = CreateObject("VBScript.RegExp")
End If
numsOnly = vbNullString
With rgx
.Global = True
.MultiLine = False
.Pattern = "[0-9]{1,5}$"
If .test(str) Then
numsOnly = CLng(.Execute(str)(0))
End If
End With
End Function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With