Code:
Sub Main()
If Not TypeOf ThisApplication.ActiveDocument Is AssemblyDocument Then
MessageBox.Show("Please run this rule inside an assembly.", "iLogic")
Exit Sub
End If Dim asmDoc As AssemblyDocument = ThisApplication.ActiveDocument
Dim selOcc As ComponentOccurrence = Nothing
If asmDoc.SelectSet.Count > 0 AndAlso TypeOf asmDoc.SelectSet.Item(1) Is ComponentOccurrence Then
selOcc = asmDoc.SelectSet.Item(1)
Else
MessageBox.Show("Select a part in the assembly first.", "iLogic")
Exit Sub
End If
Dim newFile As String = selOcc.Definition.Document.FullFileName
Dim replacedCount As Integer = 0
For Each occ As ComponentOccurrence In asmDoc.ComponentDefinition.Occurrences.AllLeafOccurrences
If occ Is selOcc Then Continue For
Dim docPath As String = occ.Definition.Document.FullFileName
If String.Equals(docPath, newFile, StringComparison.OrdinalIgnoreCase) Then Continue For
Dim baseName As String = System.IO.Path.GetFileNameWithoutExtension(docPath)
If HasTargetSuffix(baseName, 2, 10) Then
Dim keepMatrix As Matrix = occ.Transformation.Copy()
occ.Replace(newFile, False)
occ.Transformation = keepMatrix
replacedCount += 1
End If
Next
asmDoc.Update()
MessageBox.Show("Replaced occurrences: " & replacedCount, "iLogic")
End Sub
Private Function HasTargetSuffix(fileNameNoExt As String, minIdx As Integer, maxIdx As Integer) As Boolean
For i As Integer = minIdx To maxIdx
If fileNameNoExt.EndsWith("_" & i.ToString(), StringComparison.OrdinalIgnoreCase) Then
Return True
End If
Next
Return False
End Function