Hmmm...a couple of points.
1. You should NEVER issue a 'Command' call inside a reactor/event. It's possible to get into an endless loop for one thing.
2. There's no 'reliable' way in VBA to tell if a command was cancelled. So you have to deal with the possibility that the 'CommandEnded' event will not fire.
3. Also, somebody could just go into the reference manager and do nothing but view the list. Your event would fire, but the user has not attached another xref.
I think you can start to see that this is not as easy as it sounds.
However, having said that, here is a VERY quick knockup. Paste it into the 'ThisDrawing' module and give it a whirl...
Private Sub AcadDocument_EndCommand(ByVal CommandName As String)
Select Case CommandName
Case "XREF", "XATTACH"
' Get the last entity in the current space. The command *might* not have done anything...
Dim pEnt As AcadEntity
Set pEnt = ThisDrawing.CurrentSpace(ThisDrawing.CurrentSpace.Count - 1)
' Bail out if it's NOT an xref...
If Not TypeOf pEnt Is AcadExternalReference Then Exit Sub
'Gxet an extension dictionary and, if necessary, add a SortentsTable object
Dim pXDict As AcadObject
Set pXDict = ThisDrawing.CurrentSpace.GetExtensionDictionary
' Enable in-line error handling...
On Error Resume Next
Dim pSortEntsTbl As AcadSortentsTable
' Try and get a pointer to the existing (if there is one) SortEntsTable...
Set pSortEntsTbl = pXDict.GetObject("ACAD_SORTENTS")
If Err Then Err.Clear
If pSortEntsTbl Is Nothing Then
' No SortentsTable object, so add one
Set pSortEntsTbl = pXDict.AddObject("ACAD_SORTENTS", "AcDbSortentsTable")
End If
' Resume 'normal' error handling...
On Error GoTo 0
Dim entArray(0) As AcadObject
Set entArray(0) = pEnt
' Move the object to the bottom of the draworder...
pSortEntsTbl.MoveToBottom entArray
AcadApplication.Update
End Select
End Sub
Public Property Get CurrentSpace() As AcadBlock
If ThisDrawing.GetVariable("CVPORT") = 1 Then
Set CurrentSpace = PaperSpace
Else
Set CurrentSpace = ModelSpace
End If
End Property
BTW, look up AcadSortEntsTable in the AutoCAD VBA Help. This is the draworder table.
Cheers,
Glenn.