This website uses cookies to ensure you get the best experience on our website. By using our website you agree on the following Cookie Policy, Privacy Policy, and Terms Of Use
This VBA macro allows to copy the name of the components in the active assembly to the component's reference using SOLIDWORKS API.
Macro has an option to only process virtual components by settings the VIRTUAL_ONLY option to True.
Const VIRTUAL_ONLY AsBoolean = True
This macro can be useful if component names are used to store the project attributes (e.g. Part Number) as component name cannot be added to the Bill Of Materials while Component Reference can be.
Const VIRTUAL_ONLY AsBoolean = FalseDim swApp As SldWorks.SldWorks
Sub main()
Set swApp = Application.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swSelMgr As SldWorks.SelectionMgr
Set swModel = swApp.ActiveDoc
IfNot swModel IsNothingThenIf swModel.GetType() = swDocumentTypes_e.swDocASSEMBLY ThenDim swAssy As SldWorks.AssemblyDoc
Set swAssy = swModel
Dim vComps AsVariant
vComps = swAssy.GetComponents(False)
Dim i AsIntegerFor i = 0 To UBound(vComps)
Dim swComp As SldWorks.Component2
Set swComp = vComps(i)
If swComp.IsVirtual OrNot VIRTUAL_ONLY ThenDim compName AsString
compName = swComp.Name2
IfNot swComp.GetParent() IsNothingThen'if not root remove the sub-assemblies name
compName = Right(compName, Len(compName) - InStrRev(compName, "/"))
EndIfIf swComp.IsVirtual() Then'if virtual remove the context assembly name
compName = Left(compName, InStr(compName, "^") - 1)
Else'remove the index name
compName = Left(compName, InStrRev(compName, "-") - 1)
EndIf
swComp.ComponentReference = compName
EndIfNextElse
MsgBox "Active document is not an assembly"EndIfElse
MsgBox "Please open assembly document"EndIfEndSub