It looked like I was only partially right in previous code: it only works for a newly opened drawing where user never selected anything. That is, the Previous SelectionSet in AutoCAD is only updated with VBA code when the code-created selectionset calls Select()/SelectOnScrceen() method; if the selectionset is fill with AddItems(), the Previous SelectionSet in AutoCAD does not get updated, thus the code I showed does not work.
Actually I discussed this in an old thread on the same topic, and suggested a way of solving this (see my reply posted on Oct. 16th, 2018 in that thread), but never actually got time to materialize it with code. Now that facing the same issue, I wrote some VBA code in the logic as I suggested there, and as I expected: it works. The key issue here for re-use "Previous" selection set in SendCommand, we need to build an AcadSelectionSet and call its Select()/SelectOnScreen() method, so that the "Previous" selection set (actually ThisDrawing.ActiveSelectionSet) would be updated. However, you cannot directly change ThisDrawing.ActiveSelectionSet (with Add/RemoveItems()).
See code and attached video clip below.
Option Explicit
Private Const XDATA_APP As String = "MySelApp"
Public Sub DoSelection()
'' MsgBox "Prev Selected count: " & ThisDrawing.ActiveSelectionSet.Count
Dim i As Integer
'' Select all circles
Dim ents As Variant
ents = CollectTargetEntities()
If UBound(ents) < 0 Then Exit Sub
MsgBox "Targetted entity count: " & UBound(ents) + 1
'' attach XData as selection filter
SetSelectionXData ents, True
SelectByXData
'' detach Xdata as selection filter
SetSelectionXData ents, False
'' MsgBox "Prev Selected count: " & ThisDrawing.ActiveSelectionSet.Count
ThisDrawing.SendCommand "SELECT" & vbCr & "P" & vbCr & vbCr
End Sub
Private Function CollectTargetEntities() As Variant
Dim ent As AcadEntity
Dim i As Integer
Dim ents() As AcadEntity
For Each ent In ThisDrawing.ModelSpace
If TypeOf ent Is AcadCircle Then
ReDim Preserve ents(i)
Set ents(i) = ent
i = i + 1
End If
Next
CollectTargetEntities = ents
End Function
Private Sub AttachSelectionXData(ent As AcadEntity)
Dim dataType(0 To 1) As Integer
Dim data(0 To 1) As Variant
dataType(0) = 1001: dataType(1) = 1000
data(0) = XDATA_APP: data(1) = "Xdata for selection"
ent.SetXData dataType, data
End Sub
Private Sub DetachSelectionXData(ent As AcadEntity)
Dim dataType(0) As Integer
Dim data(0) As Variant
dataType(0) = 1001
data(0) = XDATA_APP
ent.SetXData dataType, data
End Sub
Private Sub SelectByXData()
Dim groupCode(0) As Integer
Dim dataCode(0) As Variant
groupCode(0) = 1001
dataCode(0) = XDATA_APP
ThisDrawing.ActiveSelectionSet.Select acSelectionSetAll, , , groupCode, dataCode
'' MsgBox "Selected: " & ss.Count
End Sub
Private Sub SetSelectionXData(ents As Variant, attach As Boolean)
Dim i As Integer
Dim ent As AcadEntity
For i = 0 To UBound(ents)
Set ent = ents(i)
If attach Then
AttachSelectionXData ent
Else
DetachSelectionXData ent
End If
Next
End Sub