for each.. next alternative to loop through modelspace entities

for each.. next alternative to loop through modelspace entities

GilesPhillips
Collaborator Collaborator
2,447 Views
2 Replies
Message 1 of 3

for each.. next alternative to loop through modelspace entities

GilesPhillips
Collaborator
Collaborator

I've got some code that currently uses a for each Entity in AcadDocument.modelspace .... next Entity type construct to loop through modelspace entities in a specified document. 

However a rewrite has it replacing some pesky mtext with dtext, which then crashes the for-each loop as the next entity in it's list has been deleted.

 

Is there a better way to do this?- I need to loop through all the modelspace block references (not fussed about the rest, the text is picked up and modified as a side function related to the blocks).  I can't use selection sets as this code needs to run independently of what's on the screen.

 

Can I rephrase my for-each loop to be more resilient to stuff getting deleted off it's list?

 

thanks for any thoughts..

 

G

ACad, MEP, Revit, 3DS Max
0 Likes
Accepted solutions (1)
2,448 Views
2 Replies
Replies (2)
Message 2 of 3

norman.yuan
Mentor
Mentor
Accepted solution

You only loop through ModelSpace once to IDENTIFY your target entities and store them aside, say, an array. After the loop, as long as the array is not empty, you do whatever with the entities in the array. Code would be like:

 

Dim i As Integer

Dim blks() As AcadBlockReference

Dim ent As AcadEntity

Dim blk As AcadBlockReference

 

For Each ent In ThisDrawing.ModelSpace

    If TypeOf ent Is AcadBlockReference Then

         Set blk = ent

         '' You then test if the block is the target block, likely by its name

         If UCase(ent.EffectiveName)="MyTargetBlock" Then

               Redim Preserve blks(i)

               set blks(i) = blk

               i = i + 1

         End If

    End If

Next

 

If i > 0 Then

   DoSomethingWithFoundBlocks blks

End If

Norman Yuan

Drive CAD With Code

EESignature

0 Likes
Message 3 of 3

GilesPhillips
Collaborator
Collaborator
Hi Norman - thanks for this.

I think my code needs a bit of an efficiency drive- putting the block references into an array for later processing sounds like the right approach.

G
ACad, MEP, Revit, 3DS Max
0 Likes