I have a column of cells with text which I want to sort alphabetically. But not all cells should be sorted by their first characters. In these cells the character by which they should be sorted is formatted with a (single) underline.
Now I want to create an auxiliary column which contains only
- for strings that have at least one char underlined: the (rest of the) string, starting with the underlined character
- for strings without underlined char: the full string
Example columns
I got some VBA code together which looks reasonable to me (with help from ChatGPT:-):
Function GetUnderlinedText(inputText As String) As String
Dim cell As Range
Dim underlinedCharIndex As Long
Dim underlinedText As String
' Get the reference to the cell
Set cell = Application.Caller
' Find the index of the first underlined character
underlinedCharIndex = FindUnderlinedChar(inputText)
' If underlined character found, return the portion of text starting from that character
If underlinedCharIndex > 0 Then
underlinedText = Mid(inputText, underlinedCharIndex)
Else
underlinedText = inputText
End If
' Return the underlined portion of the text
GetUnderlinedText = underlinedText
End Function
Function FindUnderlinedChar(inputText As String) As Long
Dim i As Long
Dim char As String
' Iterate through each character of the text
For i = 1 To Len(inputText)
char = Mid(inputText, i, 1)
' Check if the character is underlined
If IsUnderlined(inputText, i) Then
' Return the index of the underlined character
FindUnderlinedChar = i
Exit Function
End If
Next i
' If no underlined character found, return 0
FindUnderlinedChar = 0
End Function
Function IsUnderlined(inputText As String, position As Long) As Boolean
' Check if the character at the specified position is underlined
If Range("A1").Characters(position, 1).Font.Underline = xlUnderlineStyleSingle Then
IsUnderlined = True
Else
IsUnderlined = False
End If
End Function
Where I am stuck now is the Function IsUnderlined
, which always returns TRUE.
In the debugger I can verify that Range("A1").Characters(position, 1).Font.Underline
never changes its value of -4142 (= xlUnderlineStyleNone), even as I iterate through the characters.
Can anyone help what is wrong here?
user24612418 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.