Macros/General/004
TDF LibreOffice Document Liberation Project Community Blogs Weblate Nextcloud Redmine Ask LibreOffice Donate
Description
The macro presented here is intended to show how to remove unused custom styles from a document.
The macro starts by accessing the "style families". Depending on the type of document these can be CharacterStyles, ParagraphStyles, FrameStyles, PageStyles, NumberingStyles, CellStyles, ShapeStyles.[1]
The code below searches through the cell styles of a Calc sheet, in which the CellStyles collection is looped through. For each element, the methods isUserDefined and isInUse are used to test if it is a custom style used or not.[2]
The only particularity is that we browse the collection "backwards" from n to zero to avoid problems (since we delete elements from the browsed collection).
Code
In LibreOffice Basic:
Option Explicit
Sub delete_unused_styles ()
Dim oStylesF As Object
Dim oStyles As Object
Dim oStyle As Object
Dim i As Integer
oStylesF = ThisComponent.getStyleFamilies
If oStylesF.hasByName("CellStyles") Then
oStyles = oStylesF.getByName("CellStyles")
For i = UBound(oStyles.ElementNames) To 0 Step -1
oStyle = oStyles.getByName(oStyles.ElementNames(i))
If oStyle.isUserDefined And Not(oStyle.isInUse) Then
oStyle = Nothing
oStyles.removeByName(oStyles.ElementNames(i))
End If
Next i
MsgBox "Done!"
Else
MsgBox "No user-defined style families found..."
End If
End Sub ' delete_unused_styles