Search code examples
unolibreoffice-basic

libre office macro find replace formatted text


I want to go through a document and find all center aligned text and delete it, I can setup formatted text on the find and replace tool, but when I record, it doesn't save formatting... does anyone know how to edit the basic code to do this? also is the open office documentation compatible with libre office.


Solution

  • Recording in OpenOffice generates dispatcher code, which usually isn't very good. It's better to use the UNO API when writing macros. Here is some code that does what you want:

    Sub DeleteCenteredLines
        oDoc = ThisComponent
        Dim vDescriptor, vFound
        ' Create a descriptor from a searchable document.
        vDescriptor = oDoc.createSearchDescriptor()
        ' Set the text for which to search and other 
        With vDescriptor
          .searchString = ""
          .searchAll=True
        End With
        Dim srchAttributes(0) As New com.sun.star.beans.PropertyValue
        srchAttributes(0).Name = "ParaAdjust"
        srchAttributes(0).Value = com.sun.star.style.ParagraphAdjust.CENTER
        vDescriptor.SetSearchAttributes(srchAttributes())
        ' Find the first one
        vFound = oDoc.findFirst(vDescriptor)
        Do While Not IsNull(vFound)
            vFound.setPropertyValue("ParaAdjust", com.sun.star.style.ParagraphAdjust.LEFT)
            oTC = oDoc.Text.createTextCursorByRange(vFound)
            oTC.gotoStartOfParagraph(false)
            oTC.gotoEndOfParagraph(true)
            oTC.String = ""
            oTC.goRight(1,true)
            oTC.String = ""
            vFound = oDoc.findNext( vFound.End, vDescriptor)
        Loop
    End Sub
    

    Check out http://www.pitonyak.org/AndrewMacro.odt for examples of many common tasks. In my experience, looking for examples in this document is usually easier than trying to record macros and make sense of what was recorded.

    This works for OpenOffice as well as LibreOffice. Generally the API is the same for both.