After a long and rather epic journey, the problem has finally been solved!
I would like to express my sincere gratitude to everyone who took the time to read my questions, test ideas, write code, suggest improvements, and patiently share their knowledge.
Each suggestion, even when it was not the final solution, helped me better understand the problem and brought me one step closer to the answer. The final macro is the result of a collective effort, and I truly appreciate the generosity and expertise of this community.
Thank you, Carlos Florentino, JJH, Lupp, and everyone else who contributed along the way. Your willingness to help a stranger is what makes communities like Ask LibreOffice so valuable.
For the benefit of anyone who may encounter the same problem in the future, I am also sharing the final version of the macro that successfully solved it.
Option Explicit
Sub OrganizarColunaF
Dim oDoc As Object
Dim oSheet As Object
Dim oCursor As Object
Dim oCell As Object
Dim oRange As Object
Dim numeros() As Double
Dim ultimaLinha As Long
Dim quantidade As Long
Dim linha As Long
Dim texto As String
oDoc = ThisComponent
oSheet = oDoc.CurrentController.ActiveSheet
' Determine the last used row.
oCursor = oSheet.createCursor()
oCursor.gotoEndOfUsedArea(True)
ultimaLinha = oCursor.RangeAddress.EndRow
' Allocate space for numeric values.
ReDim numeros(0 To ultimaLinha)
quantidade = 0
' Scan column F starting at F1.
For linha = 0 To ultimaLinha
oCell = oSheet.getCellByPosition(5, linha)
texto = Trim(oCell.String)
If texto <> "" Then
If IsNumeric(texto) Then
numeros(quantidade) = CDbl(texto)
quantidade = quantidade + 1
End If
End If
Next linha
' Clear the old contents of column F.
oRange = oSheet.getCellRangeByPosition(5, 0, 5, ultimaLinha)
oRange.clearContents( _
com.sun.star.sheet.CellFlags.VALUE _
+ com.sun.star.sheet.CellFlags.DATETIME _
+ com.sun.star.sheet.CellFlags.STRING _
+ com.sun.star.sheet.CellFlags.FORMULA)
' Sort the numbers.
If quantidade > 1 Then
OrdenarNumeros numeros(), quantidade
End If
' Rewrite the sorted numbers from F1 downward.
For linha = 0 To quantidade - 1
oCell = oSheet.getCellByPosition(5, linha)
oCell.Value = numeros(linha)
Next linha
' Return the cursor to F1.
oDoc.CurrentController.select( _
oSheet.getCellRangeByName("F1"))
End Sub
Sub OrdenarNumeros(numeros() As Double, quantidade As Long)
Dim intervalo As Long
Dim i As Long
Dim temporario As Double
intervalo = quantidade \ 2
Do While intervalo > 0
For i = intervalo To quantidade - 1
temporario = numeros(i)
Dim j As Long
j = i
Do While j >= intervalo
If numeros(j - intervalo) <= temporario Then
Exit Do
End If
numeros(j) = numeros(j - intervalo)
j = j - intervalo
Loop
numeros(j) = temporario
Next i
intervalo = intervalo \ 2
Loop
End Sub
Please accept my heartfelt thanks and my deepest appreciation.
With my best regards,
Osmario Avila