How to quickly and efficient remove unused customize styles in document?

My job involves processing many large files daily. Each large file contains over 1500 pages, and within each document, there is an abundance of custom styles that are not in use. Nearly every file has about 500-600 unused custom styles. I use the following code to remove these custom, unused styles, which requires iterating through all the document’s styles, excluding the built-in ones, and then searching for these styles throughout the content of all documents. It is important to note that VBA does not support multithreading. The lack of multithreading support greatly reduces efficiency. My question is, apart from the code below, are there any more efficient algorithms to solve this problem?

Sub DeleteUnusedStyles()
    On Error Resume Next
    Dim oStyle As style, count 
    For Each oStyle In ActiveDocument.styles
        If oStyle.BuiltIn = False Then
            With ActiveDocument.Content.Find
                .ClearFormatting 
                .style = CVar(oStyle.NameLocal) 
                .Execute FindText:="", Format:=True 
                 If.Found = False Then
                    oStyle.Delete
                End If
            End With
        End If
    Next oStyle
  
End Sub

On this site you may find some threads for the topic of converting files to pdf. It is possible to run parallel copies of LibreOffice with separate (temporary) user-profiles to convert files.
This is multi-process instead of multi-threading, but it may help.
.
PS: VBA is an M$ environment not available inside LibreOffice, here we have only StarBASIC and of course also Python, JavaScript etc.

Your suggestion is really good, I will study it carefully, and if the experience is good, I will give up using MS Word to process documents.

A late remark: ending with so many unused styles is frequently the consequence of storing the document as a .docx file. If this is the case, cleaning the style dictionary does not fix the basis problem. If you continue so, new custom files will pop up inevitably. Working with any application in non-native format creates issues.

Always mentioning OS name, precise LO version and save format helps narrowing down the problem.

Caution: first try in some copy documents.

Sub remove_styles_not_use()

	doc = ThisComponent
	
	For Each style_familie In doc.StyleFamilies
		For Each style In style_familie
			If style.isUserDefined() And Not style.isInUse() Then
				style_familie.removeByName(style.Name)
			End If
		Next
	Next
	
End Sub
2 Likes

elmau: Thank you for your code, the efficiency of the code is really high. It helped me solve a big problem. Surprisingly, the formats saved by LibreOffice are also perfectly compatible with Word.

1 Like

I’m sorry,
I wanted to respond to another post and I responded to this one and I don’t know how to delete my response.