Option Explicit


Sub saveAsODS()

    Dim FilterNames(1,2) As String, sResult As String

    Dim sPath As String, sDirectory As String, sFile As String


    ' Filters.

    FilterNames(0,0) = "Planilha ODF" : FilterNames(0,1) = "*.ods" : FilterNames(0,2) = "calc8"

    FilterNames(1,0) = "Any type" : FilterNames(1,1) = "*.*" : FilterNames(1,2) = ""

    sPath = ConvertToURL(ThisComponent.getSheets().getByIndex(0).getCellRangeByName("A1").getString())


    ' Get filename and directory name from cell A1.

    sDirectory=DirName(sPath)

    sFile=BaseName(sPath)


    ' Open the file saving dialogue.

    GlobalScope.BasicLibraries.LoadLibrary("Tools")

    sResult = StoreDocument(ThisComponent, FilterNames, sFile, sDirectory)


    ' Check the result.

    If sResult = "" Then

       MsgBox "File not saved", MB_ICONEXCLAMATION, "Error"

    Else

       MsgBox "File saved as " + ConvertFromURL(sResult), MB_OK, "Success"

    EndIf

End Sub


Function FileNamePosition(sPath As string) As Long

    ' Find the last ”/” character.

    Dim lPos As Long

    lPos=0

    Do

       FileNamePosition=lPos

       lPos=InStr(lPos+1, sPath, "/")

    Loop While lPos>0

End Function


Function BaseName(sPath As string) As String

    BaseName=Right(sPath, Len(sPath)-FileNamePosition(sPath))

End Function


Function DirName(sPath As string) As String

    DirName=Left(sPath, FileNamePosition(sPath)-1)

End Function