I want to sort a datafield by three different columns, C, G, and H. C is fiber number 1-864, G, is Distance in Feet, H, is a status column, and that one I would want only the “Live” ones on the top. Update, I have the code not erroring, but it isn’t working either. The captions of the commandbutton are not updating which may be causing the sorting to not work because the Fiber column is already sorted before being imported.
Update: The Sorting is working. When I manually manipulate the Fiber Case with the other column numbers, the areas get sorted correctly. It’s the Updating of the Caption to cycle through the different sort Cases that is the issue.
Erroring here: SortData SortCriteria(NextIndex - 1)
Compile error byref argument type mismatch on SortCriteria is Highlighted.
Sub CommandButton2_Click()
Dim CommandButton As Shape
Dim SortCriteria As Variant
Dim CurrentCaption As String
Dim NextIndex As Integer
SortCriteria = Array("Fiber", "Distance", "Stat")
' Ensure the button is correctly identified
On Error Resume Next
Set CommandButton = ActiveSheet.Shapes("CommandButton2")
On Error GoTo 0
If CommandButton Is Nothing Then
MsgBox "CommandButton2 not found on the active sheet.", vbCritical
Exit Sub
End If
With CommandButton.OLEFormat.Object.Object
CurrentCaption = .Caption
NextIndex = Application.Match(CurrentCaption, SortCriteria, 0)
If IsError(NextIndex) Then
NextIndex = 1 ' Default to the first criteria if not found
Else
NextIndex = NextIndex Mod UBound(SortCriteria) + 1
End If
.Caption = SortCriteria(NextIndex - 1)
End With
SortData SortCriteria(NextIndex - 1)
End Sub
Public Sub SortData(ws As Worksheet, criteria As String)
Dim SortColumn As Integer
Dim SortOrder As XlSortOrder
Dim lastRow As Long
Set ws = ActiveSheet
lastRow = ws.Range("A3:Q1000").Find(What:="*", _
After:=ws.Range("A3"), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
Set SortRange = ws.Range("A3:Q" & lastRow)
Select Case criteria
Case "Fiber"
SortColumn = 3 ' Column C
Case "Distance"
SortColumn = 7 ' Column G
Case "Stat"
SortColumn = 5 ' Column E
Case Else
MsgBox "Invalid sort criteria.", vbCritical
Exit Sub
End Select
With ws.Sort
.SortFields.Clear
.SortFields.Add Key:=ws.Cells(3, SortColumn), Order:=xlAscending
.SetRange SortRange
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
1