A family of Microsoft word processing software products for creating web, email, and print documents.
Welcome to Microsoft Q&A forum
Regarding your concern, I suggest to check:
1.Enhance StyleExists to Use a More Robust Check
Instead of relying solely on For Each, try accessing the style directly via poStyles(oStyleName) with error handling to detect its existence, as this may catch styles missed by enumeration.
Private Function StyleExists(Name As String) As Boolean
Dim oStyle As Style
On Error Resume Next
Set oStyle = poStyles(Name)
StyleExists = (Not oStyle Is Nothing)
On Error GoTo 0
End Function
2.Fix DoOneParagraph with Robust Error Handling
Modify DoOneParagraph to handle errors more reliably and debug the issue. Also, ensure NoFault is initialized and errors are logged for clarity.
Private Function DoOneParagraph(clsStyle As TSpecStyle, oStyleName As String) As Style
Dim oStyle As Style
Dim NoFault As Boolean
NoFault = True ' Initialize to True
On Error Resume Next
Set oStyle = poStyles(oStyleName) ' Try accessing style first
If Err.Number = 0 And Not oStyle Is Nothing Then
' Style exists, use it
ElseIf Err.Number = 5173 Or Err.Number = 5834 Then
' Style exists but is inaccessible (e.g., corrupted or template-based)
Set oStyle = poStyles(oStyleName)
Err.Clear
Else
' Style does not exist, try adding it
Err.Clear
Set oStyle = poStyles.Add(oStyleName, wdStyleTypeParagraph)
If Err.Number <> 0 Then
Debug.Print "Error adding style '" & oStyleName & "': " & Err.Number & " - " & Err.Description
NoFault = False
End If
End If
On Error GoTo 0
If Not oStyle Is Nothing Then
NoFault = clsStyle.Prepare(oStyle)
Else
NoFault = False
End If
If NoFault Then
Set DoOneParagraph = oStyle
Else
Set DoOneParagraph = Nothing ' Use Nothing instead of Null
End If
End Function
**3.**Debug Style Existence:
In the VBA Immediate Window, run:
On Error Resume Next: Debug.Print ActiveDocument.Styles("Help6B1").InUse, ActiveDocument.AttachedTemplate.Styles("Help6B1").InUse: On Error GoTo 0
4.Test in a New Document:
Create a new .docx document and test the code to rule out document or template corruption.
If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.