Here is a macro to LOCK/ UNLOCK external references on PRESELECTED components

My workflow often includes designing components in context and then locking external references. After years of manually locking/ unlocking each individual component I finally got around to make me a macro to do that on all preselected components as on the picture below.

Quick and dirty but it works for me.

And here is the macro:

' ******************************************************************************
' LOCK/ UNLOCK external references on PRESELECTED components
' ******************************************************************************
Dim swApp As Object

Dim Part As Object
Dim boolstatus As Boolean
Dim longstatus As Long, longwarnings As Long

Public swSelMgr         As SldWorks.SelectionMgr

Dim mdoc() As SldWorks.ModelDoc2

Sub main()

Dim i As Long
Dim j As Long
Dim k As Integer


Set swApp = Application.SldWorks

Set Part = swApp.ActiveDoc

Set swSelMgr = Part.SelectionManager
j = swSelMgr.GetSelectedObjectCount2(-1)

If j < 1 Then MsgBox ("Exiting... Nothing selected. Preselect components and try again"): Exit Sub

k = MsgBox("""Yes"" to LOCK the components" & vbNewLine & """No"" to UNLOCK" & vbNewLine & """Cancel"" for DO NOTHING", vbYesNoCancel, "Lock/Unlock")

If k = vbCancel Then MsgBox ("Exiting... no action taken"): Exit Sub

On Error Resume Next

ReDim mdoc(j)
For i = 1 To j
Set mdoc(i) = swSelMgr.GetSelectedObjectsComponent3(i, -1).GetModelDoc2
Next

If k = vbYes Then
  For i = 1 To j
    mdoc(i).LockAllExternalReferences
  Next
End If
If k = vbNo Then
  For i = 1 To j
    mdoc(i).UnlockAllExternalReferences
  Next
End If

MsgBox "Done!"

End Sub

SolidworksApi/macros