Looking at Paul's code it is important to note that the .InUse property of a style is essentially useless as it returns TRUE if the style was ever used in the document or template. It doesn't reflect whether the style is currently in use in the document. To see if the style is currently being used in the document we need to do a find as a secondary test.
Code:
Sub RemoveStyles()
'Searches main story of current document and deletes all unused User-Defined Styles
Dim msg As String, DelMsg As String, myDoc As Document, sty As Variant
Set myDoc = ActiveDocument
msg = "Styles in use:" & vbCr
DelMsg = "Styles deleted:" & vbCr
For Each sty In myDoc.Styles
If sty.InUse = True Then
With myDoc.Content.Find
.ClearFormatting
.Text = ""
.Style = sty
.Execute Format:=True
If .Found = True Then
msg = msg & sty & ", "
Else
If sty.BuiltIn Then GoTo Catcher
DelMsg = DelMsg & sty & ", "
sty.Delete
End If
End With
End If
Catcher:
Next sty
MsgBox msg & vbCr & vbCr & DelMsg
End Sub
Lup
You need to reduce ambiguity by assigning ActiveDocument to a variable before you start your search in the AttachedTemplate. The way I've approached the same requirement is to open the template and load the stylenames to a dictionary object before looping through the styles in ActiveDocument. As the code fragment in the below instance sits in the AttachedTemplate, I used ThisDocument to identify the template.
Code:
Set aDocDirty = ActiveDocument
aDocDirty.UpdateStyles 'make sure all template styles included before beginning
WordBasic.DisableAutoMacros 1 'Disables auto macros
Set aDoc = Documents.Add(Template:=ThisDocument.FullName)
WordBasic.DisableAutoMacros 0 'Enables auto macros
'build dictionary of template custom stylenames
Set dictTemplateStyles = New Scripting.Dictionary
For Each aSty In aDoc.Styles
Select Case aSty.Type
Case wdStyleTypeCharacter, wdStyleTypeLinked, wdStyleTypeParagraph, wdStyleTypeParagraphOnly
If Not aSty.BuiltIn Then
sName = Split(aSty.NameLocal, ",")(0)
dictTemplateStyles.Add sName, aSty.NameLocal 'namelocal includes existing aliases
'Debug.Print sName, dictTemplateStyles(sName)
End If
End Select
Next aSty
Debug.Print "Number of custom styles in template: " & dictTemplateStyles.Count
aDoc.Close SaveChanges:=False
Set dictMap = GetDictMap(aDocDirty)
Debug.Print dictMap.Count
'Now iterate through aDocDirty styles