Does anyone know of a macro that will traverse the top level assembly feature tree and delete any components that were suppressed on open because of missing references?
This could be done a lot of ways but this is possibly the simplest. It simply looks to see if a component's file path exists. If not, it deletes that component. To use the code below, you will need to add a reference to Microsoft Scripting Runtime via Tools-->References within the VB Editor.
'Deletes all missing components in an assembly
'Preconditions: Assembly is open.
'Note: You can control whether this macro affects only top level assembly
' components via the TOP_LEVEL_ONLY constant.
'Written by Keith Rice
Const TOP_LEVEL_ONLY As Boolean = True
Dim fso As New FileSystemObject
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swAssy As SldWorks.AssemblyDoc
Dim swComp As SldWorks.Component2
Dim vComps As Variant
Dim i As Integer
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
If swModel Is Nothing Then Exit Sub
If swModel.GetType <> swDocASSEMBLY Then Exit Sub
Set swAssy = swModel
vComps = swAssy.GetComponents(TOP_LEVEL_ONLY)
If IsEmpty(vComps) Then Exit Sub
For i = 0 To UBound(vComps)
Set swComp = vComps(i)
If fso.FileExists(swComp.GetPathName) = False Then
SolidWorks API Training and Services
There probably is but it would be something that if your interested in learning VBA that should not be too hard to write. There are examples for traversing the tree, all you need do is add a deletion routine.
Thanks Keith, when I run this though I'm getting a Run-time error '52': Bad file name or number on line 35 in your code above. Also if I want it to look through all levels of the assembly do I just modify the Const TOP_LEVEL_ONLY to be False?
Yes. TOP_LEVEL_ONLY = false, would return an array of all components.That error may be caused because the component's model file does exist (hence why it's not found). That file must reside in an external storage source (flash disk, network connection) that is not available. Instead of using dir, use File Object System.Add Microsoft Scripting as a reference.
Dim fso As FileSystemObject
Set fso = New Scripting.FileSystemObject
If Not fso.FileExists(swComp.GetPathName) Then
You're welcome! You can tick Keith's response as the correct one. I have just helped out with an improvement. Cheers,Amenwww.cadhero.com
Thank you, Amen.
Funny, I specifically used Dir() to avoid using FileSystemObject so I wouldn't have to type out extra instructions on how to add the reference. Anyway, I did some research and it looks like Andy's error is related to permissions. I'm not sure why FileSystemObject.FileExsts() would get around that, but apparently it does.
Anyway, I have updated my code to use FileSystemObject.
Retrieving data ...