sdalrymple
New Member
- Joined
- Nov 3, 2017
- Messages
- 4
Hello! I'm new to VBA and first would like to thank everyone posting codes that anyone can use!!
I've found this very useful code to alphabetically sort words within cell separated by a comma. I'm wondering if i can tweak this to reverse sort? (Z-A instead of A-Z)
Function StrSort(ByVal sInp As String, Optional bDescending As Boolean = False) As String
' sorts a comma-delimited string
Dim asSS() As String ' substring array
Dim sSS As String ' temp string for exchange
Dim n As Long
Dim i As Long
Dim j As Long
Dim Val1 As Long
Dim Val2 As Long
asSS = Split(sInp, ",")
n = UBound(asSS)
For i = 0 To n
asSS(i) = Trim(asSS(i))
Next i
If n <= 1 Then
StrSort = sInp
Else
For i = 0 To n - 1
For j = i + 1 To n
If InStr(asSS(j), "-") > 0 Then
Val1 = Val(Left(asSS(j), InStr(asSS(j), "-") - 1))
Else
Val1 = Val(asSS(j))
End If
If InStr(asSS(i), "-") > 0 Then
Val2 = Val(Left(asSS(i), InStr(asSS(i), "-") - 1))
Else
Val2 = Val(asSS(i))
End If
If (Val1 < Val2) Xor bDescending Then
sSS = asSS(i)
asSS(i) = asSS(j)
asSS(j) = sSS
End If
Next j
Next i
StrSort = Join(asSS, ", ")
End If
End Function
I've found this very useful code to alphabetically sort words within cell separated by a comma. I'm wondering if i can tweak this to reverse sort? (Z-A instead of A-Z)
Function StrSort(ByVal sInp As String, Optional bDescending As Boolean = False) As String
' sorts a comma-delimited string
Dim asSS() As String ' substring array
Dim sSS As String ' temp string for exchange
Dim n As Long
Dim i As Long
Dim j As Long
Dim Val1 As Long
Dim Val2 As Long
asSS = Split(sInp, ",")
n = UBound(asSS)
For i = 0 To n
asSS(i) = Trim(asSS(i))
Next i
If n <= 1 Then
StrSort = sInp
Else
For i = 0 To n - 1
For j = i + 1 To n
If InStr(asSS(j), "-") > 0 Then
Val1 = Val(Left(asSS(j), InStr(asSS(j), "-") - 1))
Else
Val1 = Val(asSS(j))
End If
If InStr(asSS(i), "-") > 0 Then
Val2 = Val(Left(asSS(i), InStr(asSS(i), "-") - 1))
Else
Val2 = Val(asSS(i))
End If
If (Val1 < Val2) Xor bDescending Then
sSS = asSS(i)
asSS(i) = asSS(j)
asSS(j) = sSS
End If
Next j
Next i
StrSort = Join(asSS, ", ")
End If
End Function